/**
 * translateCtrl - Controller for translate
 */
// 多语言控制
function translateCtrl($translate, $scope) {
    $scope.changeLanguage = function (langKey) {
        $translate.use(langKey);
        $scope.language = langKey;
    };
}

//
function mainCtrl($scope, $http, $sce) {
    $scope.menuRegexp = /_PRIVILEGE/g;
    $http({
        method: 'post',
        url: '/user/getMenuList'
    }).then(function (value) {
        $scope.menuList = value.data;
    });
}

// 主页控制1
function homePageCtrl($scope, $http, $timeout) {
    /**
     * Data for Bar chart
     */
    var context = document.getElementById('bar').getContext('2d');
    context.canvas.height = 70;
    context.canvas.width = 300;
    $scope.labels = [getDateStr(-7), getDateStr(-6), getDateStr(-5), getDateStr(-4), getDateStr(-3), getDateStr(-2), getDateStr(-1)];
    $scope.series = ['成功', '失败'];
    $scope.data = [
        [1, 2, 3, 4, 5, 6, 7],
        [7, 6, 5, 4, 3, 2, 1]
    ];
    $scope.colors = ['rgb(26,179,148)', 'rgb(220,220,220)'];
    $timeout(function () {
        $http({
            method: 'post',
            url: '/getDatas'
        }).then(function (response) {
            $scope.data = [
                response.data.firstData,
                response.data.secondData
            ];
            angular.element('#barIbox').toggleClass('sk-loading');
        });
    });
}

// 主页控制2
function homePagePieCtrl($scope, $http, $timeout) {
    /**
     * Data for Pie chart
     */
    $scope.labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'];
    $scope.data = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
    $scope.colors = [
        '#6666CC',
        '#6699CC',
        '#66CCCC',
        '#66FFCC',
        '#9966CC',
        '#9999CC',
        '#99CCCC',
        '#99FFCC',
        '#CC66CC',
        '#CC99CC',
        '#CCCCCC',
        '#CCFFCC',
        '#FF66CC',
        '#FF99CC',
        '#FFCCCC'
    ];
    $timeout(function () {
        angular.element('#pieIbox').toggleClass('sk-loading');
    });
}

// 主页控制3
function homePageDoughnutFCtrl($scope, $http, $timeout) {
    $scope.labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'];
    $scope.data = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1];
    $scope.colors = [
        '#666699',
        '#669999',
        '#66CC99',
        '#66FF99',
        '#996699',
        '#999999',
        '#99CC99',
        '#99FF99',
        '#CC6699',
        '#CC9999',
        '#CCCC99',
        '#CCFF99',
        '#FF6699',
        '#FF9999',
        '#FFCC99'
    ];
    $timeout(function () {
        angular.element('#doughnutFIbox').toggleClass('sk-loading');
    });
}

// 主页控制4
function homePageDoughnutRCtrl($scope, $http, $timeout) {
    $scope.labels = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n'];
    $scope.data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14];
    $scope.colors = [
        '#666666',
        '#669966',
        '#66CC66',
        '#66FF66',
        '#996666',
        '#999966',
        '#99CC66',
        '#99FF66',
        '#CC6666',
        '#CC9966',
        '#CCCC66',
        '#CCFF66',
        '#FF6666',
        '#FF9966',
        '#FFCC66'
    ];
    $timeout(function () {
        angular.element('#doughnutRIbox').toggleClass('sk-loading');
    });
}

// 风控限次管理 $scope作用域 $timeout $httpSvc http请求 $NgTableParams ngtable, toaster 弹窗
function riskIndefinitelyCtrl($scope, $timeout, $uibModal, httpSvc, NgTableParams, toaster) {
    // 获取全部参数
    httpSvc.getData('post', '/risk/getInit').then(function (value) {
        $scope.merchant = value.merchant;   // 商户信息
        $scope.siteurl = value.siteurl;     // 域名
        $scope.acquirer = value.acquirer;   // 收单机构
        $scope.limitConstant = value.limitConstant;    // 限制元素
        $scope.statusConstant = value.statusConstant;   // 状态
        $scope.init = value;   // 整个value对象
    });
    // 显示数据
    $timeout(function () {
        $scope.$watch('init', function (newVal) {
            if (newVal !== undefined && newVal != null) {
                angular.element('.ibox-content').addClass('sk-loading');
                httpSvc.getData('post', '/risk/getIndefinitely').then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    for (var i = 0; i < value.length; i++) {
                        // 限制元素
                        for (var j = 0; j < $scope.init.limitConstant.length; j++) {
                            if (value[i].element === $scope.init.limitConstant[j].id) {
                                value[i]['refLimitName'] = $scope.init.limitConstant[j].name;
                                break;
                            }
                        }
                        // 状态
                        switch (value[i].status) {
                            case 0:
                                value[i]['statusName'] = '禁用';
                                break;
                            case 1:
                                value[i]['statusName'] = '启用';
                                break;
                            default:
                                break;
                        }
                        // 名称、类型名称
                        switch (value[i].refType) {
                            case 0:
                                value[i]['refTypeName'] = '通用';
                                value[i]['refName'] = '通用';
                                break;
                            case 1:
                                // 收单机构名称
                                value[i]['refTypeName'] = '收单机构';
                                for (var j = 0; j < $scope.init.acquirer.length; j++) {
                                    value[i].refId += '';
                                    if (value[i].refId === $scope.init.acquirer[j].id) {
                                        value[i]['refName'] = $scope.init.acquirer[j].name;
                                        break;
                                    }
                                }
                                break;
                            case 2:
                                // 商户
                                value[i]['refTypeName'] = '商户';
                                for (var j = 0; j < $scope.init.merchant.length; j++) {
                                    if (value[i].refId === $scope.init.merchant[j].id) {
                                        value[i]['refName'] = $scope.init.merchant[j].name;
                                        break;
                                    }
                                }
                                break;
                            case 3:
                                // 域名
                                value[i]['refTypeName'] = '域名';
                                for (var j = 0; j < $scope.init.siteurl.length; j++) {
                                    if (value[i].refId === $scope.init.siteurl[j].id) {
                                        value[i]['refName'] = $scope.init.siteurl[j].siteUrl;
                                        break;
                                    }
                                }
                                break;
                            default:
                                break;
                        }

                        // function generalprint() {
                        //     value[i]['refTypeName'] = '通用';
                        //     value[i]['refName'] = '通用';
                        // }
                        // function coreAcquirerprint() {
                        //     value[i]['refTypeName'] = '收单机构';
                        //     for (var j = 0; j < $scope.init.acquirer.length; j++) {
                        //         value[i].refId += '';
                        //         value[i].refId == $scope.init.acquirer[j].id ? value[i]['refName'] = $scope.init.acquirer[j].name : value[i]['refName'] = '';
                        //     }
                        // }
                        // function merchantprint() {
                        //     value[i]['refTypeName'] = '商户';
                        //     for (var j = 0; j < $scope.init.merchant.length; j++) {
                        //         value[i].refId == $scope.init.merchant[j].id ? value[i]['refName'] = $scope.init.merchant[j].name : value[i]['refName'] = '';
                        //     }
                        // }
                        // function siteurlprint() {
                        //     value[i]['refTypeName'] = '域名';
                        //     for (var j = 0; j < $scope.init.siteurl.length; j++) {
                        //         value[i].refId == $scope.init.siteurl[j].id ? value[i]['refName'] = $scope.init.siteurl[j].siteUrl : value[i]['refName'] = '';
                        //     }
                        // }
                        // let typeobj = {
                        //    0:generalprint,
                        //    1:coreAcquirerprint,
                        //    2:merchantprint,
                        //    3:siteurlprint
                        // };
                        // if(typeobj in typeobj){
                        //     typeobj[typeobj]();
                        // }
                    }
                    $scope.indefinitelyTable = new NgTableParams({}, {
                        dataset: value
                    });
                });
            }
        })
    })
    // 查询
    $scope.search = function (indefinitely) {
        angular.extend($scope.indefinitelyTable.filter(), indefinitely);
    };
    // 重置
    $scope.resetForm = function () {
        $scope.indefinitely = {};
        $scope.indefinitelyTable.filter({});
    };
    // 下拉框筛选
    $scope.$watch('indefinitely.refTypeName', function (newVal) {
        switch (newVal) {
            case '通用':
                //$scope.initParam = [{id:0,name:'通用'}];
                //$scope.initParam = [];
                $scope.Name = '通用';
                break;
            case '收单机构':
                //$scope.initParam = $scope.init.acquirer;
                $scope.Name = '';
                break;
            case '商户':
                //$scope.initParam = $scope.init.merchant;
                $scope.Name = '';
                break;
            case '域名':
                // $scope.initParam = $scope.init.siteurl;
                $scope.Name = '';
                break;
            default:
                // $scope.initParam = [];
                $scope.Name = '';
        }
    });
    // 启用与禁用操作
    $scope.locked = function ($event, row) {
        var locked_flag;
        angular.element($event.target).hasClass('active') ? locked_flag = 0 : locked_flag = 1;
        httpSvc.getData('post', '/risk/getindefinitelyLocked', {
            id: row.id,
            status: locked_flag
        }).then(function (value) {
            if (value === true) {
                toaster.pop({
                    type: 'success',
                    title: '风控限次管理更新成功',
                    body: '更新状态成功'
                });
                angular.element($event.target).toggleClass('active');
                angular.element($event.target).toggleClass('btn-primary');
                angular.element($event.target).toggleClass('btn-danger');
                angular.element($event.target).hasClass('active') ?
                    angular.element($event.target).text('启用') :
                    angular.element($event.target).text('禁用');
                tableReload();
            } else {
                toaster.pop({
                    type: 'error',
                    title: '风控限次管理更新失败',
                    body: '更新状态失败'
                });
            }
        })
    }
    // type：0为添加,1为更新,2为删除
    $scope.showModal = function (risk, type) {
        var modalInstance = $uibModal.open({
            // 模板URL
            templateUrl: '/views/risk/risk_indefinitely_modal',
            // 模板 Ctrl
            controller: 'riskIndefinitelyModalCtrl',
            // modal大小：lg
            // size:
            // 给modal传递参数
            resolve: {
                risk: function () {
                    return risk;
                },
                type: function () {
                    return type;
                },
                init: function () {
                    return $scope.init;
                }
            }
        });
        modalInstance.result.then(function () {
            // 点击关闭执行函数
            tableReload();
        }, function () {
            // 点击modal外部后关闭modal执行函数
            tableReload();
        });
    };
    // 弹框的额外事件
    function tableReload() {
                angular.element('.ibox-content').addClass('sk-loading');
                httpSvc.getData('post', '/risk/getIndefinitely').then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    for (var i = 0; i < value.length; i++) {
                        // 限制元素
                        for (var j = 0; j < $scope.init.limitConstant.length; j++) {
                            if (value[i].element === $scope.init.limitConstant[j].id) {
                                value[i]['refLimitName'] = $scope.init.limitConstant[j].name;
                                break;
                            }
                        }
                        // 状态
                        switch (value[i].status) {
                            case 0:
                                value[i]['statusName'] = '禁用';
                                break;
                            case 1:
                                value[i]['statusName'] = '启用';
                                break;
                            default:
                                break;
                        }
                        // 名称、类型名称
                        switch (value[i].refType) {
                            case 0:
                                value[i]['refTypeName'] = '通用';
                                value[i]['refName'] = '通用';
                                break;
                            case 1:
                                // 收单机构名称
                                value[i]['refTypeName'] = '收单机构';
                                for (var j = 0; j < $scope.init.acquirer.length; j++) {
                                    value[i].refId += '';
                                    if (value[i].refId === $scope.init.acquirer[j].id) {
                                        value[i]['refName'] = $scope.init.acquirer[j].name;
                                        break;
                                    }
                                }
                                break;
                            case 2:
                                // 商户
                                value[i]['refTypeName'] = '商户';
                                for (var j = 0; j < $scope.init.merchant.length; j++) {
                                    if (value[i].refId === $scope.init.merchant[j].id) {
                                        value[i]['refName'] = $scope.init.merchant[j].name;
                                        break;
                                    }
                                }
                                break;
                            case 3:
                                // 域名
                                value[i]['refTypeName'] = '域名';
                                for (var j = 0; j < $scope.init.siteurl.length; j++) {
                                    if (value[i].refId === $scope.init.siteurl[j].id) {
                                        value[i]['refName'] = $scope.init.siteurl[j].siteUrl;
                                        break;
                                    }
                                }
                                break;
                            default:
                                break;
                        }

                        // function generalprint() {
                        //     value[i]['refTypeName'] = '通用';
                        //     value[i]['refName'] = '通用';
                        // }
                        // function coreAcquirerprint() {
                        //     value[i]['refTypeName'] = '收单机构';
                        //     for (var j = 0; j < $scope.init.acquirer.length; j++) {
                        //         value[i].refId += '';
                        //         value[i].refId == $scope.init.acquirer[j].id ? value[i]['refName'] = $scope.init.acquirer[j].name : value[i]['refName'] = '';
                        //     }
                        // }
                        // function merchantprint() {
                        //     value[i]['refTypeName'] = '商户';
                        //     for (var j = 0; j < $scope.init.merchant.length; j++) {
                        //         value[i].refId == $scope.init.merchant[j].id ? value[i]['refName'] = $scope.init.merchant[j].name : value[i]['refName'] = '';
                        //     }
                        // }
                        // function siteurlprint() {
                        //     value[i]['refTypeName'] = '域名';
                        //     for (var j = 0; j < $scope.init.siteurl.length; j++) {
                        //         value[i].refId == $scope.init.siteurl[j].id ? value[i]['refName'] = $scope.init.siteurl[j].siteUrl : value[i]['refName'] = '';
                        //     }
                        // }
                        // let typeobj = {
                        //    0:generalprint,
                        //    1:coreAcquirerprint,
                        //    2:merchantprint,
                        //    3:siteurlprint
                        // };
                        // if(typeobj in typeobj){
                        //     typeobj[typeobj]();
                        // }
                    }
                    $scope.indefinitelyTable = new NgTableParams({}, {
                        dataset: value
                    });
                });
    }
    // 删除用户数据
    // $scope.deleteIt = function (row) {
    //     httpSvc.getData('post', '/risk/getdelete', row.id).then(function (value) {
    //         if (value === 1) {
    //             toaster.pop({
    //                 type: 'success',
    //                 title: '风控限次管理更新成功',
    //                 body: '删除数据成功'
    //             });
    //         } else {
    //             toaster.pop({
    //                 type: 'error',
    //                 title: '风控限次管理更新失败',
    //                 body: '删除数据失败'
    //             });
    //         }
    //     });
    // }
    // 批量删除
    var idArr = [];
    $scope.deleteFlag = true;
    $scope.collectSelectRows = function ($event, id) {
        var isChecked = angular.element($event.target).prop("checked");
        if (isChecked == true) {
            idArr.push(id);
            $scope.deleteFlag = false;
        } else if (isChecked == false) {
            idArr.pop(id);
            if (idArr === undefined || idArr.length == 0) {
                $scope.deleteFlag = true;
            } else {
                $scope.deleteFlag = false;
            }
        }
    }
    $scope.batchDel = function () {
        httpSvc.getData('post', '/risk/getindefinitelyBatchDel', idArr).then(function (value) {
            if (value > 0) {
                toaster.pop({
                    type: 'success',
                    title: '数据删除',
                    body: '删除成功！'
                });
                $scope.deleteFlag = true;
            } else {
                toaster.pop({
                    type: 'error',
                    title: '数据删除',
                    body: '删除失败！'
                });
                $scope.deleteFlag = true;
            }
            idArr = [];
            tableReload();
        });
    }
}

// 风控限次管理的面板控制器
function riskIndefinitelyModalCtrl($scope, $uibModalInstance, httpSvc, toaster, risk, type, init) {
    $scope.risk = risk;
    if (risk !== undefined) {
        $scope.risk.status = risk.status + '';
    }
    $scope.type = type;
    $scope.init = init;
    $scope.$watch('risk.refType', function (newVal) {
        newVal = Number(newVal);
        switch (newVal) {
            case 0:
                $scope.initParam = [{id: 0, name: '通用'}];
                break;
            case 1:
                $scope.initParam = init.acquirer;
                break;
            case 2:
                $scope.initParam = init.merchant;
                break;
            case 3:
                $scope.initParam = init.siteurl;
                break;
            default:
                // $scope.initParam = [];
                break;
        }
    });
    // 关闭
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    // 添加操作
    $scope.insertRiskLimit = function (risk, type) {
        httpSvc.getData('post','/risk/getindefinitelyAddCount',risk).then(function (value) {
            if(value == 0){
                httpSvc.getData('post', '/risk/getadd', risk).then(function (value) {
                    if(value === 1) {
                        toaster.pop({
                            type: 'success',
                            title: '风控限次管理添加成功',
                            body: '添加数据成功'
                        });
                    }else{
                        toaster.pop({
                            type: 'error',
                            title: '风控限次管理添加失败',
                            body: '添加数据失败'
                        });
                    }
                    $uibModalInstance.dismiss();
                });
            } else {
                  toaster.pop({
                       type:  'error',
                       title: '不符合风控规则',
                       body: '添加数据失败'
                  });
                $uibModalInstance.dismiss();
             }
        });
    };
    // 更新操作
    $scope.updateRiskLimit = function (risk, type) {
        httpSvc.getData('post','/risk/getupdate',risk).then(function (value) {
            if(value === 1){
                toaster.pop({
                    type: 'success',
                    title: '风控限次管理更新成功',
                    body: '更新数据成功'
                });
            }else {
                toaster.pop({
                    type: 'error',
                    title: '风控限次管理更新失败',
                    body: '更新数据失败'
                });
            }
            $uibModalInstance.dismiss();
        });
    };
    //面板验证
    $scope.typeBlur = $scope.nameBlur = $scope.limitBlur = function ($event,type) {
        verification(type,$event.target);
    };
    $scope.successBlur = $scope.failBlur = $scope.hourBlur = $scope.statusBlur = $scope.successupdateBlur = $scope.failupdateBlur = $scope.hourupdateBlur = $scope.statusupdateBlur = function ($event, element) {
        verification(element, $event.target);
    };
    $scope.typeupdateFocus = $scope.nameupdateFocus = $scope.limitupdateFocus = function ($event, type) {
        verification(type, $event.target);
    };
    $scope.nextDisabled = function (myFormupdate) {
        return (myFormupdate.typeupdate.$pristine && myFormupdate.nameupdate.$pristine && myFormupdate.limitupdate.$pristine && myFormupdate.successupdate.$pristine && myFormupdate.failupdate.$pristine && myFormupdate.hourupdate.$pristine && myFormupdate.statusupdate.$pristine) ||
            (!myFormupdate.typeupdate.$valid || !myFormupdate.nameupdate.$valid || !myFormupdate.limitupdate.$valid || !myFormupdate.successupdate.$valid || !myFormupdate.failupdate.$valid || !myFormupdate.hourupdate.$valid || !myFormupdate.statusupdate.$valid );
    };
}

// 风控限额管理
function riskLimitCtrl($scope,$timeout,$uibModal,httpSvc,NgTableParams,toaster) {
    // 获取全部参数
    httpSvc.getData('post','/risk/getInit').then(function (value) {
        $scope.merchant = value.merchant;   // 商户信息
        $scope.siteurl = value.siteurl;     // 域名
        $scope.acquirer = value.acquirer;   // 收单机构
        $scope.statusConstant = value.statusConstant;   // 状态
        $scope.payType = value.credit //信用卡类型
        $scope.init = value; // 整个value对象

    });
    // 查询
    $scope.search = function (limit) {
        angular.extend($scope.limitTable.filter(), limit);
    };
    // 重置
    $scope.resetForm = function () {
        $scope.limit = {};
        $scope.limitTable.filter({});
    };
    // 显示数据在表格
    $timeout(function () {
        $scope.$watch('init',function (newVal) {
            if (!(newVal !== undefined && newVal != null)) {
                return;
            }
            angular.element('.ibox-content').addClass('sk-loading');
            httpSvc.getData('post', '/risk/getLimit').then(function (value) {
                angular.element('.ibox-content').removeClass('sk-loading');
                for (var i = 0; i < value.length; i++) {
                    // 状态
                    switch (value[i].status) {
                        case 1:
                            value[i]['statusName'] = '启用';
                            break;
                        case 0:
                            value[i]['statusName'] = '禁用';
                            break;
                        default:
                            break;
                    }
                    // 限定卡
                    switch (value[i].payType) {
                        case 'sys00000000061000001':
                            value[i]['paytypeName'] = 'Visa';
                            break;
                        case 'sys00000000061000002':
                            value[i]['paytypeName'] = 'Master';
                            break;
                        case 'sys00000000061000003':
                            value[i]['paytypeName'] = 'Master';
                            break;
                        case 'sys00000000061000004':
                            value[i]['paytypeName'] = 'Master';
                            break;
                        case 'sys00000000061000005':
                            value[i]['paytypeName'] = 'Master';
                            break;
                        case 'sys00000000061000006':
                            value[i]['paytypeName'] = 'Master';
                            break;
                        case 'sys00000000061000007':
                            value[i]['paytypeName'] = 'Master';
                            break;
                        case 'sys00000000061000008':
                            value[i]['paytypeName'] = 'Master';
                            break;
                        default:
                            break;
                    }
                    // 限定类型
                    switch (value[i].limitType) {
                        case 0:
                            value[i]['limitName'] = '笔';
                            break;
                        case 1:
                            value[i]['limitName'] = '日';
                            break;
                        case 2:
                            value[i]['limitName'] = '月';
                            break;
                        case 3:
                            value[i]['limitName'] = '年';
                            break;
                        default:
                            break;
                    }
                    // 名称与类型
                    switch (value[i].refType) {
                        case 0:
                            value[i]['typeName'] = '通用';
                            value[i]['refName'] = '通用';
                            break;
                        case 1:
                            value[i]['typeName'] = '收单机构';
                            for (var j = 0; j < $scope.init.acquirer.length; j++) {
                                value[i].refId += '';
                                if (value[i].refId === $scope.init.acquirer[j].id) {
                                    value[i]['refName'] = $scope.init.acquirer[j].name;
                                    break;
                                }
                            }
                            break;
                        case 2:
                            value[i]['typeName'] = '商户';
                            for (var j = 0; j < $scope.init.merchant.length; j++) {
                                if (value[i].refId === $scope.init.merchant[j].id) {
                                    value[i]['refName'] = $scope.init.merchant[j].name;
                                    value[i]['refId'] = $scope.init.merchant[j].id;
                                    break;
                                }
                            }
                            break;
                        case 3:
                            value[i]['typeName'] = '域名';
                            for (var j = 0; j < $scope.init.siteurl.length; j++) {
                                if (value[i].refId === $scope.init.siteurl[j].id) {
                                    value[i]['refName'] = $scope.init.siteurl[j].siteUrl;
                                    break;
                                }
                            }
                            break;
                        default:
                            break;
                    }
                }
                // 表格
                $scope.limitTable = new NgTableParams({}, {
                    dataset: value
                });
            });
        })
    })
    // 弹窗注册
    $scope.showModal = function (risk,type) {
        var modalInstance = $uibModal.open({
            // 模板url
            templateUrl: '/views/risk/risk_limit_modal',
            controller: 'riskLimitModalCtrl',
            resolve: {
                risk: function () {
                    return risk;
                },
                type: function () {
                    return type;
                },
                init: function () {
                    return $scope.init;
                }
            }
        });
        modalInstance.result.then(function () {
            // 点击关闭执行函数
            tableReload();
        }, function () {
            // 点击modal外部后关闭modal执行函数
            tableReload();
        });
    }
    // 监听查询条件
    $scope.$watch('limit.typeName',function (newVal) {
        switch (newVal) {
            case '通用':
                //$scope.initParam = [{id:0,name:'通用'}];
                // $scope.initParam = [];
                $scope.Name = '通用';
                break;
            case '收单机构':
                //$scope.initParam = $scope.init.acquirer;
                $scope.Name = '';
                break;
            case '商户':
                // $scope.initParam = $scope.init.merchant;
                $scope.Name = '';
                break;
            case '域名':
                // $scope.initParam = $scope.init.siteurl;
                $scope.Name = '';
                break;
            default:
                // $scope.initParam = [];
                $scope.Name = '';
        }
    });
    // 点击面板之外的事件
    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/risk/getLimit').then(function (value) {
            for (var i = 0; i < value.length; i++) {
                // 状态
                switch (value[i].status) {
                    case 1:
                        value[i]['statusName'] = '启用';
                        break;
                    case 0:
                        value[i]['statusName'] = '禁用';
                        break;
                    default:
                        break;
                }
                // 限定卡
                switch (value[i].payType) {
                    case 'sys00000000061000001':
                        value[i]['paytypeName'] = 'Visa';
                        break;
                    case 'sys00000000061000002':
                        value[i]['paytypeName'] = 'Master';
                        break;
                    case 'sys00000000061000003':
                        value[i]['paytypeName'] = 'Master';
                        break;
                    case 'sys00000000061000004':
                        value[i]['paytypeName'] = 'Master';
                        break;
                    case 'sys00000000061000005':
                        value[i]['paytypeName'] = 'Master';
                        break;
                    case 'sys00000000061000006':
                        value[i]['paytypeName'] = 'Master';
                        break;
                    case 'sys00000000061000007':
                        value[i]['paytypeName'] = 'Master';
                        break;
                    case 'sys00000000061000008':
                        value[i]['paytypeName'] = 'Master';
                        break;
                    default:
                        break;
                }
                // 限定类型
                switch (value[i].limitType){
                    case 0:
                        value[i]['limitName'] = '笔';
                        break;
                    case 1:
                        value[i]['limitName'] = '日';
                        break;
                    case 2:
                        value[i]['limitName'] = '月';
                        break;
                    case 3:
                        value[i]['limitName'] = '年';
                        break;
                    default:
                        break;
                }
                // 名称与类型
                switch (value[i].refType){
                    case 0:
                        value[i]['typeName'] = '通用';
                        value[i]['refName'] = '通用';
                        break;
                    case 1:
                        value[i]['typeName'] = '收单机构';
                        for (var j = 0; j < $scope.init.acquirer.length; j++) {
                            value[i].refId += '';
                            if(value[i].refId === $scope.init.acquirer[j].id) {
                                value[i]['refName'] = $scope.init.acquirer[j].name;
                                break;
                            }
                        }
                        break;
                    case 2:
                        value[i]['typeName'] = '商户';
                        for (var j = 0; j < $scope.init.merchant.length; j++) {
                            if (value[i].refId === $scope.init.merchant[j].id) {
                                value[i]['refName'] = $scope.init.merchant[j].name;
                                break;
                            }
                        }
                        break;
                    case 3:
                        value[i]['typeName'] = '域名';
                        for (var j = 0; j < $scope.init.siteurl.length; j++) {
                            if (value[i].refId === $scope.init.siteurl[j].id) {
                                value[i]['refName'] = $scope.init.siteurl[j].siteUrl;
                                break;
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            $scope.limitTable.settings({
                dataset: value
            });
            $scope.totalItems = value.length;
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
    // 启用与禁用模块
    $scope.locked = function ($event, row) {
        var locked_flag;
        angular.element($event.target).hasClass('active') ? locked_flag = 0 : locked_flag = 1;
        httpSvc.getData('post', '/risk/getlimitLocked', {
            id: row.id,
            status: locked_flag
        }).then(function (value) {
            if (value === true) {
                toaster.pop({
                    type: 'success',
                    title: '风控限额管理更新成功',
                    body: '更新状态成功'
                });
                angular.element($event.target).toggleClass('active');
                angular.element($event.target).toggleClass('btn-primary');
                angular.element($event.target).toggleClass('btn-danger');
                angular.element($event.target).hasClass('active') ?
                    angular.element($event.target).text('启用') :
                    angular.element($event.target).text('禁用');
                tableReload();
            } else {
                toaster.pop({
                    type: 'error',
                    title: '风控限额管理更新失败',
                    body: '更新状态失败'
                });
            }
        })
    }
    // 删除用户数据
    // $scope.deleteIt = function (row) {
    //     httpSvc.getData('post', '/risk/getlimitDeleted', row.id).then(function (value) {
    //         if (value === true) {
    //             toaster.pop({
    //                 type: 'success',
    //                 title: '风控限额管理更新成功',
    //                 body: '删除数据成功'
    //             });
    //         } else {
    //             toaster.pop({
    //                 type: 'success',
    //                 title: '风控限额管理更新失败',
    //                 body: '删除数据失败'
    //             });
    //         }
    //     });
    // }
    // 批量删除
    var idArr = [];
    $scope.deleteFlag = true;
    $scope.collectSelectRows = function ($event, id) {
        var isChecked = angular.element($event.target).prop("checked");
        if (isChecked == true) {
            idArr.push(id);
            $scope.deleteFlag = false;
        } else if (isChecked == false) {
            idArr.pop(id);
            if (idArr === undefined || idArr.length == 0) {
                $scope.deleteFlag = true;
            } else {
                $scope.deleteFlag = false;
            }
        }
    }
    // 批量删除请求方法
    $scope.batchDel = function () {
        httpSvc.getData('post', '/risk/getlimitBatchDel', idArr).then(function (value) {
            if (value > 0) {
                toaster.pop({
                    type: 'success',
                    title: '数据删除',
                    body: '删除成功！'
                });
                $scope.deleteFlag = true;
            } else {
                toaster.pop({
                    type: 'error',
                    title: '数据删除',
                    body: '删除失败！'
                });
                $scope.deleteFlag = true;
            }
            idArr = [];
            tableReload();
        });
    }
}

// 风控限额管理的面板控制器
function riskLimitModalCtrl($scope, risk, type, toaster, httpSvc, $uibModalInstance, init) {
    $scope.type = type;
    $scope.init = init;
    $scope.risk = risk;
    if (risk !== undefined) {
        $scope.risk.refType = risk.refType + '';  // 隐式转换
        $scope.risk.refId = risk.refId + '';
        $scope.risk.status = risk.status + '';
        $scope.risk.limitType = risk.limitType + '';
    }
    $scope.$watch('risk.refType',function (newVal) {
        switch (newVal) {
            case '0':
                $scope.initParam = [{id: 0, name: '通用'}];
                break;
            case '1':
                $scope.initParam = init.acquirer;
                break;
            case '2':
                $scope.initParam = init.merchant;
                break;
            case '3':
                $scope.initParam = init.siteurl;
                break;
            default:
                $scope.initParam = [];
        }
    })
    // 关闭
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    // 新增操作
    $scope.insertRiskQuota = function (risk,type) {
        httpSvc.getData('post','/risk/getlimitAddCount',risk).then(function (value) {
            if(value === 0){
                httpSvc.getData('post','/risk/getlimitAdd',risk).then(function (value) {
                    if(value === true) {
                        toaster.pop({
                            type: 'success',
                            title: '风控限额管理添加成功',
                            body: '添加数据成功'
                        });
                    }else{
                        toaster.pop({
                            type: 'error',
                            title: '风控限额管理添加失败',
                            body: '添加数据失败'
                        });
                    }
                    $uibModalInstance.dismiss();
                });
            } else {
                toaster.pop({
                    type: 'error',
                    title: '不符合风控规则',
                    body: '添加数据失败'
                });
                $uibModalInstance.dismiss();
            }
        });
    }
    // 更新操作
    $scope.updateRiskQuota = function (risk, type) {
        httpSvc.getData('post', '/risk/getlimitUpdate', risk).then(function (value) {
            if (value === true) {
                toaster.pop({
                    type: 'success',
                    title: '风控限额管理更新成功',
                    body: '更新数据成功'
                });
            } else {
                toaster.pop({
                    type: 'error',
                    title: '风控限额管理更新失败',
                    body: '更新数据失败'
                });
            }
            $uibModalInstance.dismiss();
        });
    }
    // 面板验证操作
    $scope.typeBlur = $scope.nameBlur = $scope.limitnameBlur = $scope.limitmoneyBlur = $scope.limitpercentBlur = $scope.limitstatusBlur = $scope.paytypenameBlur = function ($event, type) {
        verification(type, $event.target);
    };
    $scope.typeupdateFocus = $scope.nameupdateFocus = $scope.limitnameupdateFocus = $scope.limitmoneyupdate = $scope.limitpercentupdate = $scope.statusupdate = $scope.paytypenameupdateFocus = function ($event, type) {
        verification(type, $event.target);
    };
    $scope.nextDisabled = function (myFormUpdate) {
        return (myFormUpdate.typeupdate.$pristine && myFormUpdate.nameupdate.$pristine && myFormUpdate.limitnameupdate.$pristine && myFormUpdate.limitmoneyupdate.$pristine && myFormUpdate.limitpercentupdate.$pristine && myFormUpdate.statusupdate.$pristine && myFormUpdate.paytypenameupdate.$pristine) ||
            (!myFormUpdate.typeupdate.$valid || !myFormUpdate.nameupdate.$valid || !myFormUpdate.limitnameupdate.$valid || !myFormUpdate.limitmoneyupdate.$valid || !myFormUpdate.limitpercentupdate.$valid || !myFormUpdate.statusupdate.$valid || !myFormUpdate.paytypenameupdate.$valid);
    };
}

// 风控拒绝管理
function riskRefusedCtrl($scope, $timeout, $uibModal, httpSvc, NgTableParams, toaster) {
    // 获取全部参数
    httpSvc.getData('post', '/risk/getInit').then(function (value) {
        $scope.merchant = value.merchant; // 商户信息
        $scope.siteurl = value.siteurl;   // 域名
        $scope.acquirer = value.acquirer;  // 收单机构
        $scope.statusConstant = value.statusConstant; // 状态
        $scope.stopConstant = value.stopConstant; // 拒绝元素
        $scope.country = value.country; // 国家
        $scope.issuer = value.issuer; // 发卡行
        $scope.init = value;
    });
    // 查询
    $scope.search = function (refused) {
        angular.extend($scope.refusedTable.filter(), refused);
    };
    // 重置
    $scope.resetForm = function () {
        $scope.refused = {};
        $scope.refusedTable.filter({});
    };
    // 显示数据
    $timeout(function () {
        $scope.$watch('init', function (newVal) {
            if (newVal !== undefined && newVal != null) {
                angular.element('.ibox-content').addClass('sk-loading');
                httpSvc.getData('post', '/risk/getRefused').then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    for (var i = 0; i < value.length; i++) {
                        // 状态
                        switch (value[i].status) {
                            case 1:
                                value[i]['statusName'] = '启用';
                                break;
                            case 0:
                                value[i]['statusName'] = '禁用';
                                break;
                            default:
                                break;
                        }
                        // 拒绝元素
                        for (var j = 0; j < $scope.init.stopConstant.length; j++) {
                            if (value[i].element == $scope.init.stopConstant[j].id) {
                                value[i]['refuseName'] = $scope.init.stopConstant[j].name;
                                break;
                            }
                        }
                        // 限制元素
                        switch (value[i].element) {
                            case 'sys00000000102000001':
                                // 发卡行
                                for (var j = 0; j < $scope.init.issuer.length; j++) {
                                    if (value[i].elementValue == $scope.init.issuer[j].firstValue) {
                                        value[i]['elementName'] = $scope.init.issuer[j].name;
                                    }
                                }
                                break;
                            case 'sys00000000102000003':
                                // 国家
                                for (var j = 0; j < $scope.init.country.length; j++) {
                                    if (value[i].elementValue == $scope.init.country[j].firstValue) {
                                        value[i]['elementName'] = $scope.init.country[j].name;
                                    }
                                }
                                break;
                            default:
                                value[i]['elementName'] = value[i].elementValue;
                                break;
                        }
                        // 名称、类型名称
                        switch (value[i].refType) {
                            case 0:
                                value[i]['refTypeName'] = '通用';
                                value[i]['refName'] = '通用';
                                break;
                            case 1:
                                // 收单机构名称
                                value[i]['refTypeName'] = '收单机构';
                                for (var j = 0; j < $scope.init.acquirer.length; j++) {
                                    value[i].refId += '';
                                    if (value[i].refId === $scope.init.acquirer[j].id) {
                                        value[i]['refName'] = $scope.init.acquirer[j].name;
                                        break;
                                    }
                                }
                                break;
                            case 2:
                                // 商户
                                value[i]['refTypeName'] = '商户';
                                for (var j = 0; j < $scope.init.merchant.length; j++) {
                                    if (value[i].refId === $scope.init.merchant[j].id) {
                                        value[i]['refName'] = $scope.init.merchant[j].name;
                                        break;
                                    }
                                }
                                break;
                            case 3:
                                // 域名
                                value[i]['refTypeName'] = '域名';
                                for (var j = 0; j < $scope.init.siteurl.length; j++) {
                                    if (value[i].refId === $scope.init.siteurl[j].id) {
                                        value[i]['refName'] = $scope.init.siteurl[j].siteUrl;
                                        break;
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    // 表格
                    $scope.refusedTable = new NgTableParams({}, {
                        dataset: value
                    });
                })
            }
        })
    })
    // 面板弹窗
    $scope.showModal = function (risk, type) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/risk/risk_refused_modal',
            controller: 'riskRefusedModalCtrl',
            resolve: {
                risk: function () {
                    return risk;
                },
                type: function () {
                    return type;
                },
                init: function () {
                    return $scope.init;
                }
            }
        });
        modalInstance.result.then(function () {
            // 点击关闭执行函数
            tableReload();
        }, function () {
            // 点击modal外部后关闭modal执行函数
            tableReload();
        });
    }
    // 面板额外点击事件
    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/risk/getRefused').then(function (value) {
            for (var i = 0; i < value.length; i++) {
                // 状态
                switch (value[i].status) {
                    case 1:
                        value[i]['statusName'] = '启用';
                        break;
                    case 0:
                        value[i]['statusName'] = '禁用';
                        break;
                    default:
                        break;
                }

                // 拒绝元素
                for (var j = 0; j < $scope.init.stopConstant.length; j++) {
                    if (value[i].element == $scope.init.stopConstant[j].id) {
                        value[i]['refuseName'] = $scope.init.stopConstant[j].name;
                        break;
                    }
                }

                switch (value[i].element) {
                    case 'sys00000000102000001':
                        // 发卡行
                        for (var j = 0; j < $scope.init.issuer.length; j++) {
                            if (value[i].elementValue == $scope.init.issuer[j].firstValue) {
                                value[i]['elementName'] = $scope.init.issuer[j].name;
                            }
                        }
                        break;
                    case 'sys00000000102000003':
                        // 国家
                        for (var j = 0; j < $scope.init.country.length; j++) {
                            if (value[i].elementValue == $scope.init.country[j].firstValue) {
                                value[i]['elementName'] = $scope.init.country[j].name;
                            }
                        }
                        break;
                    default:
                        value[i]['elementName'] = value[i].elementValue;
                        break;
                }

                // 名称、类型名称
                switch (value[i].refType) {
                    case 0:
                        value[i]['refTypeName'] = '通用';
                        value[i]['refName'] = '通用';
                        break;
                    case 1:
                        // 收单机构名称
                        value[i]['refTypeName'] = '收单机构';
                        for (var j = 0; j < $scope.init.acquirer.length; j++) {
                            value[i].refId += '';
                            if (value[i].refId === $scope.init.acquirer[j].id) {
                                value[i]['refName'] = $scope.init.acquirer[j].name;
                                break;
                            }
                        }
                        break;
                    case 2:
                        // 商户
                        value[i]['refTypeName'] = '商户';
                        for (var j = 0; j < $scope.init.merchant.length; j++) {
                            if (value[i].refId === $scope.init.merchant[j].id) {
                                value[i]['refName'] = $scope.init.merchant[j].name;
                                break;
                            }
                        }
                        break;
                    case 3:
                        // 域名
                        value[i]['refTypeName'] = '域名';
                        for (var j = 0; j < $scope.init.siteurl.length; j++) {
                            if (value[i].refId === $scope.init.siteurl[j].id) {
                                value[i]['refName'] = $scope.init.siteurl[j].siteUrl;
                                break;
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            $scope.refusedTable.settings({
                dataset: value
            });
            $scope.totalItems = value.length;
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
    // 监听查询条件
    $scope.$watch('refused.refuseName', function (newVal) {
        switch (newVal) {
            case "发卡行":
                $scope.initRefusedParam = $scope.init.issuer;
                $scope.Namerefused = '';
                break;
            case "商务卡":
                $scope.initRefusedParam = [{id: 0, name: 'true'}, {id: 0, name: 'false'}];
                $scope.Namerefused = '';
                break;
            case "国家":
                $scope.initRefusedParam = $scope.init.country;
                $scope.Namerefused = '';
                break;
            case "IP":
                $scope.initRefusedParam = [];
                $scope.Namerefused = '通用';
                break;
            case "邮箱":
                $scope.initRefusedParam = [];
                $scope.Namerefused = '通用';
                break;
            case "卡号":
                $scope.initRefusedParam = [];
                $scope.Namerefused = '通用';
                break;
            default:
                $scope.initRefusedParam = [];
                $scope.Namerefused = '';
                break;
        }
    });
    // 监听查询条件
    $scope.$watch('refused.refTypeName', function (newVal) {
        switch (newVal) {
            case '通用':
                // $scope.initParam = [];
                $scope.Name = '通用';
                break;
            case '收单机构':
                // $scope.initParam = $scope.init.acquirer;
                $scope.Name = '';
                break;
            case '商户':
                // $scope.initParam = $scope.init.merchant;
                $scope.Name = '';
                break;
            case '域名':
                // $scope.initParam = $scope.init.siteurl;
                $scope.Name = '';
                break;
            default:
                //$scope.initParam = [];
                $scope.Name = '';
        }
    });
    // 启用与禁用模块
    $scope.locked = function ($event, row) {
        var locked_flag;
        angular.element($event.target).hasClass('active') ? locked_flag = 0 : locked_flag = 1;
        httpSvc.getData('post', '/risk/getrefusedLocked', {id: row.id, status: locked_flag}).then(function (value) {
            if (value === true) {
                toaster.pop({
                    type: 'success',
                    title: '风控拒绝管理更新成功',
                    body: '更新状态成功'
                });
                angular.element($event.target).toggleClass('active');
                angular.element($event.target).toggleClass('btn-primary');
                angular.element($event.target).toggleClass('btn-danger');
                angular.element($event.target).hasClass('active') ?
                    angular.element($event.target).text('启用') :
                    angular.element($event.target).text('禁用');
                tableReload();
            }else{
                toaster.pop({
                    type: 'error',
                    title: '风控拒绝管理更新失败',
                    body: '更新状态失败'
                });
            }
        })
    }
    // 删除数据
    // $scope.deleteIt = function (row) {
    //     httpSvc.getData('post', '/risk/getrefusedDeleted', row.id).then(function (value) {
    //         if (value === true) {
    //             toaster.pop({
    //                 type: 'success',
    //                 title: '风控拒绝管理更新成功',
    //                 body: '删除数据成功'
    //             });
    //         } else {
    //             toaster.pop({
    //                 type: 'success',
    //                 title: '风控拒绝管理更新失败',
    //                 body: '删除数据失败'
    //             });
    //         }
    //     });
    // }
    // 批量删除
    var idArr = [];
    $scope.deleteFlag = true;
    $scope.collectSelectRows = function ($event, id) {
        var isChecked = angular.element($event.target).prop("checked");
        if (isChecked == true) {
            idArr.push(id);
            $scope.deleteFlag = false;
        } else if (isChecked == false) {
            idArr.pop(id);
            if (idArr === undefined || idArr.length == 0) {
                $scope.deleteFlag = true;
            } else {
                $scope.deleteFlag = false;
            }
        }
    }
    $scope.batchDel = function () {
        httpSvc.getData('post', '/risk/getrefusedBatchDel', idArr).then(function (value) {
            if (value > 0) {
                toaster.pop({
                    type: 'success',
                    title: '数据删除',
                    body: '删除成功！'
                });
                $scope.deleteFlag = true;
            } else {
                toaster.pop({
                    type: 'error',
                    title: '数据删除',
                    body: '删除失败！'
                });
                $scope.deleteFlag = true;
            }
            idArr = [];
            tableReload();
        });
    }

}

// 风控拒绝管理的面板控制器
function riskRefusedModalCtrl($scope, risk, type, toaster, httpSvc, $uibModalInstance, init) {
    $scope.type = type;
    $scope.init = init;
    $scope.risk = risk;
    if (risk !== undefined) {
        $scope.risk.refType = risk.refType + '';  // 隐式转换
        $scope.risk.refId = risk.refId + '';
        $scope.risk.status = risk.status + '';
    }
    $scope.$watch('addriskrefused.element',function (newVal) {
        switch (newVal) {
            case " ":
                $scope.initRefusedParam = [{id: 0, name: '通用'}];
                break;
            case "sys00000000102000001":
                $scope.initRefusedParam = init.issuer;
                break;
            case "sys00000000102000002":
                $scope.initRefusedParam = [{id: 0, name: 'true'}, {id: 0, name: 'false'}]
                break;
            case "sys00000000102000003":
                $scope.initRefusedParam = init.country;
                break;
            default:
                $scope.initRefusedParam = '';
                break;
        }
    });
    $scope.$watch('risk.refType', function (newVal) {
        switch (newVal) {
            case '0':
                $scope.initParam = [{id: 0, name: '通用'}];
                break;
            case '1':
                $scope.initParam = init.acquirer;
                break;
            case '2':
                $scope.initParam = init.merchant;
                break;
            case '3':
                $scope.initParam = init.siteurl;
                break;
            default:
                $scope.initParam = [];
                break;
        }
    });
    $scope.$watch('risk.element', function (newVal) {
        switch (newVal) {
            case " ":
                $scope.initRefusedParam = [{id: 0, name: '通用'}];
                break;
            case "sys00000000102000001":
                $scope.initRefusedParam = init.issuer;
                break;
            case "sys00000000102000002":
                $scope.initRefusedParam = [{id: 0, name: 'true'}, {id: 0, name: 'false'}]
                break;
            case "sys00000000102000003":
                $scope.initRefusedParam = init.country;
                break;
            default:
                $scope.initRefusedParam = '';
                break;
        }
    });
    // 关闭
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    // 新增操作
    $scope.insertRiskRefuse = function (risk,type) {
        httpSvc.getData('post','/risk/getrefusedAddCount',risk).then(function (value) {
             if(value === 0){
                 httpSvc.getData('post','/risk/getrefusedAdd',risk).then(function (value) {
                     if(value === true) {
                         toaster.pop({
                             type: 'success',
                             title: '风控拒绝管理添加成功',
                             body: '添加数据成功'
                         });
                     }else{
                         toaster.pop({
                             type: 'error',
                             title: '风控拒绝管理添加失败',
                             body: '添加数据失败'
                         });
                     }
                     $uibModalInstance.dismiss();
                 });
             }else {
                 toaster.pop({
                     type: 'error',
                     title: '不符合风控规则',
                     body: '添加数据失败'
                 });
                 $uibModalInstance.dismiss();
             }
        });
    }
    // 更新操作
    $scope.updateRiskRefuse = function (risk, type) {
        httpSvc.getData('post', '/risk/getrefusedUpdate', risk).then(function (value) {
            if (value === true) {
                toaster.pop({
                    type: 'success',
                    title: '风控拒绝管理更新成功',
                    body: '更新数据成功'
                });
            } else {
                toaster.pop({
                    type: 'error',
                    title: '风控拒绝管理更新失败',
                    body: '更新数据失败'
                });
            }
            $uibModalInstance.dismiss();
        });
    }
    // 面板验证操作
    $scope.typeBlur = $scope.elementTypeoneBlur = $scope.nameBlur = $scope.refusedelementBlur = $scope.statusBlur = function ($event, type) {
        verification(type, $event.target);
    };
    $scope.typeupdateFocus = $scope.nameupdateFocus = $scope.refusedelementFocus = $scope.elementupdateBlur = $scope.statusupdateBlur = function ($event, type) {
        verification(type, $event.target);
    };
    $scope.nextDisabled = function (myFormupdate) {
        return (myFormupdate.typeupdate.$pristine && myFormupdate.nameupdate.$pristine && myFormupdate.refusedelementupdate.$pristine && myFormupdate.elementkey.$pristine && myFormupdate.status.$pristine) ||
            (!myFormupdate.typeupdate.$valid || !myFormupdate.nameupdate.$valid || !myFormupdate.refusedelementupdate.$valid || !myFormupdate.elementkey.$valid || !myFormupdate.status.$valid);
    };
}

// 外置风控管理
function riskOuterCtrl($scope, $timeout, $uibModal, httpSvc, NgTableParams, toaster) {
    // 获取参数
    httpSvc.getData('post', '/risk/getInit').then(function (value) {
        $scope.merchant = value.merchant // 商户信息
        $scope.siteurl = value.siteurl; // 域名
        $scope.acquirer = value.acquirer; // 收单机构
        $scope.statusConstant = value.statusConstant; // 状态
        $scope.extrisk = value.extrisk; // 风控类型
        $scope.init = value;
    });
    // 显示表格数据
    $timeout(function () {
        $scope.$watch('init', function (newVal) {
            if (newVal !== undefined && newVal != null) {
                angular.element('.ibox-content').addClass('sk-loading');
                httpSvc.getData('post', '/risk/getOuter').then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    for (var i = 0; i < value.length; i++) {
                        // 状态
                        switch (value[i].status) {
                            case 1:
                                value[i]['statusName'] = '启用';
                                break;
                            case 0:
                                value[i]['statusName'] = '禁用';
                                break;
                            default:
                                break;
                        }
                        // 名称，类型
                        switch (value[i].refType) {
                            case 0:
                                value[i]['refTypeName'] = '通用';
                                value[i]['refName'] = '通用';
                                break;
                            case 1:
                                // 收单机构名称
                                value[i]['refTypeName'] = '收单机构';
                                for (var j = 0; j < $scope.init.acquirer.length; j++) {
                                    value[i].refId += '';
                                    if (value[i].refId === $scope.init.acquirer[j].id) {
                                        value[i]['refName'] = $scope.init.acquirer[j].name;
                                        break;
                                    }
                                }
                                break;
                            case 2:
                                // 商户
                                value[i]['refTypeName'] = '商户';
                                for (var j = 0; j < $scope.init.merchant.length; j++) {
                                    if (value[i].refId === $scope.init.merchant[j].id) {
                                        value[i]['refName'] = $scope.init.merchant[j].name;
                                        break;
                                    }
                                }
                                break;
                            case 3:
                                // 域名
                                value[i]['refTypeName'] = '域名';
                                for (var j = 0; j < $scope.init.siteurl.length; j++) {
                                    if (value[i].refId === $scope.init.siteurl[j].id) {
                                        value[i]['refName'] = $scope.init.siteurl[j].siteUrl;
                                        break;
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                        // 风控类型
                        for (var j = 0; j < $scope.init.extrisk.length; j++) {
                            if (value[i].element === $scope.init.extrisk[j].id) {
                                value[i]['riskType'] = $scope.init.extrisk[j].name;
                            }
                        }
                    }
                    // 表格
                    $scope.outerTable = new NgTableParams({}, {
                        dataset: value
                    });
                })
            }
        })
    })
    // 查询
    $scope.search = function (outer) {
        angular.extend($scope.outerTable.filter(), outer);
    };
    // 重置
    $scope.resetForm = function () {
        $scope.outer = {};
        $scope.outerTable.filter({});
    };
    // 显示弹窗
    $scope.showModal = function (risk, type) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/risk/risk_outer_modal',
            controller: 'riskOuterModalCtrl',
            resolve: {
                risk: function () {
                    return risk;
                },
                type: function () {
                    return type;
                },
                init: function () {
                    return $scope.init;
                }
            }
        });
        modalInstance.result.then(function () {
            // 点击关闭执行函数
            tableReload();
        }, function () {
            // 点击modal外部后关闭modal执行函数
            tableReload();
        });
    }
    // 监听下拉选项
    $scope.$watch('outer.refTypeName', function (newVal) {
        switch (newVal) {
            case '通用':
                // $scope.initParam = [];
                $scope.Name = '通用';
                break;
            case '收单机构':
                // $scope.initParam = $scope.init.acquirer;
                $scope.Name = '';
                break;
            case '商户':
                // $scope.initParam = $scope.init.merchant;
                $scope.Name = '';
                break;
            case '域名':
                // $scope.initParam = $scope.init.siteurl;
                $scope.Name = '';
                break;
            default:
                // $scope.initParam = [];
                $scope.Name = '';
        }
    });
    // 弹窗额外点击事件
    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/risk/getOuter').then(function (value) {
            for (var i = 0; i < value.length; i++) {
                // 状态
                switch (value[i].status) {
                    case 1:
                        value[i]['statusName'] = '启用';
                        break;
                    case 0:
                        value[i]['statusName'] = '禁用';
                        break;
                    default:
                        break;
                }
                // 名称，类型
                switch (value[i].refType) {
                    case 0:
                        value[i]['refTypeName'] = '通用';
                        value[i]['refName'] = '通用';
                        break;
                    case 1:
                        // 收单机构名称
                        value[i]['refTypeName'] = '收单机构';
                        for (var j = 0; j < $scope.init.acquirer.length; j++) {
                            value[i].refId += '';
                            if (value[i].refId === $scope.init.acquirer[j].id) {
                                value[i]['refName'] = $scope.init.acquirer[j].name;
                                break;
                            }
                        }
                        break;
                    case 2:
                        // 商户
                        value[i]['refTypeName'] = '商户';
                        for (var j = 0; j < $scope.init.merchant.length; j++) {
                            if (value[i].refId === $scope.init.merchant[j].id) {
                                value[i]['refName'] = $scope.init.merchant[j].name;
                                break;
                            }
                        }
                        break;
                    case 3:
                        // 域名
                        value[i]['refTypeName'] = '域名';
                        for (var j = 0; j < $scope.init.siteurl.length; j++) {
                            if (value[i].refId === $scope.init.siteurl[j].id) {
                                value[i]['refName'] = $scope.init.siteurl[j].siteUrl;
                                break;
                            }
                        }
                        break;
                    default:
                        break;
                }
                // 风控类型
                for (var j = 0; j < $scope.init.extrisk.length; j++) {
                    if (value[i].element === $scope.init.extrisk[j].id) {
                        value[i]['riskType'] = $scope.init.extrisk[j].name;
                    }
                }
            }
            $scope.outerTable.settings({
                dataset: value
            });
            $scope.totalItems = value.length;
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
    // 启用与禁用模块
    $scope.locked = function ($event, row) {
        var locked_flag;
        angular.element($event.target).hasClass('active') ? locked_flag = 0 : locked_flag = 1;
        httpSvc.getData('post', '/risk/getouterLocked', {id: row.id, status: locked_flag}).then(function (value) {
            if (value === true) {
                toaster.pop({
                    type: 'success',
                    title: '外置风控管理更新成功',
                    body: '更新状态成功'
                });
                angular.element($event.target).toggleClass('active');
                angular.element($event.target).toggleClass('btn-primary');
                angular.element($event.target).toggleClass('btn-danger');
                angular.element($event.target).hasClass('active') ?
                    angular.element($event.target).text('启用') :
                    angular.element($event.target).text('禁用');
                tableReload();
            }else{
                toaster.pop({
                    type: 'error',
                    title: '外置风控管理更新失败',
                    body: '更新状态失败'
                });
            }
        })
    }
    // 删除数据
    // $scope.deleteIt = function (row) {
    //     httpSvc.getData('post', '/risk/getouterDeleted', row.id).then(function (value) {
    //         if (value === true) {
    //             toaster.pop({
    //                 type: 'success',
    //                 title: '外置风控管理更新成功',
    //                 body: '删除数据成功'
    //             });
    //         } else {
    //             toaster.pop({
    //                 type: 'success',
    //                 title: '外置风控管理更新失败',
    //                 body: '删除数据失败'
    //             });
    //         }
    //     });
    // }
    // 批量删除
    var idArr = [];
    $scope.deleteFlag = true;
    $scope.collectSelectRows = function ($event, id) {
        var isChecked = angular.element($event.target).prop("checked");
        if (isChecked == true) {
            idArr.push(id);
            $scope.deleteFlag = false;
        } else if (isChecked == false) {
            idArr.pop(id);
            if (idArr === undefined || idArr.length == 0) {
                $scope.deleteFlag = true;
            } else {
                $scope.deleteFlag = false;
            }
        }
    }
    $scope.batchDel = function () {
        httpSvc.getData('post', '/risk/getouterBatchDel', idArr).then(function (value) {
            if (value > 0) {
                toaster.pop({
                    type: 'success',
                    title: '数据删除',
                    body: '删除成功！'
                });
                $scope.deleteFlag = true;
            } else {
                toaster.pop({
                    type: 'error',
                    title: '数据删除',
                    body: '删除失败！'
                });
                $scope.deleteFlag = true;
            }
            idArr = [];
            tableReload();
        });
    }
}

// 外置风控管理的面板控制器
function riskOuterModalCtrl($scope, risk, type, toaster, httpSvc, $uibModalInstance, init) {
    $scope.type = type;
    $scope.init = init;
    $scope.risk = risk;
    if (risk !== undefined) {
        $scope.risk.refType = risk.refType + '';  // 隐式转换
        $scope.risk.refId = risk.refId + '';
        $scope.risk.status = risk.status + '';
    }
    $scope.$watch('risk.refType',function (newVal) {
        switch (newVal) {
            case '0':
                $scope.initParam = [{id: 0, name: '通用'}];
                break;
            case '1':
                $scope.initParam = init.acquirer;
                break;
            case '2':
                $scope.initParam = init.merchant;
                break;
            case '3':
                $scope.initParam = init.siteurl;
                break;
            default:
                $scope.initParam = [];
        }
    })
    // 关闭
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    // 新增操作
    $scope.insertRiskOuter = function (risk,type) {
        httpSvc.getData('post','/risk/getouterAddCount',risk).then(function (value) {
              if(value === 0) {
                  httpSvc.getData('post','/risk/getouterAdd',risk).then(function (value) {
                      if(value === true) {
                          toaster.pop({
                              type: 'success',
                              title: '外置风控管理添加成功',
                              body: '添加数据成功'
                          });
                          $uibModalInstance.dismiss();
                      }else{
                          toaster.pop({
                              type: 'error',
                              title: '外置风控管理添加失败',
                              body: '添加数据失败'
                          });
                          $uibModalInstance.dismiss();
                      }
                  });
              }else {
                  toaster.pop({
                      type: 'error',
                      title: '不符合风控规则',
                      body: '添加数据失败'
                  });
                  $uibModalInstance.dismiss();
              }
        });
    }
    // 更新操作
    $scope.updateRiskOuter = function (risk, type) {
        httpSvc.getData('post', '/risk/getouterUpdate', risk).then(function (value) {
            if (value === true) {
                toaster.pop({
                    type: 'success',
                    title: '外置风控管理更新成功',
                    body: '更新数据成功'
                });
            } else {
                toaster.pop({
                    type: 'error',
                    title: '外置风控管理更新失败',
                    body: '更新数据失败'
                });
            }
            $uibModalInstance.dismiss();
        });
    }
    // 面板验证
    $scope.typeBlur = function ($event, type) {
        if (verification(type, $event.target)) {
            $scope.nameMessage = '请输入类型!';
        } else {
            $scope.nameMessage = null;
        }
    }
    $scope.nameBlur = function ($event, id) {
        if (verification(id, $event.target)) {
            $scope.nameMessagea = '请输入名称!';
        } else {
            $scope.nameMessagea = null;
        }
    }
    $scope.risktypeBlur = function ($event, risktype) {
        if (verification(risktype, $event.target)) {
            $scope.nameMessageb = '请输入风控类型!';
        } else {
            $scope.nameMessageb = null;
        }
    }
    $scope.elementkeyBlur = function ($event, elementValue) {
        if (verification(elementValue, $event.target)) {
            $scope.nameMessagec = '请输入元素键值!';
        } else {
            $scope.nameMessagec = null;
        }
    }
    $scope.typeBlur = $scope.nameBlur = $scope.risktypeBlur = $scope.elementkeyBlur = $scope.statusBlur = function ($event,type) {
        verification(type,$event.target);
    };
    $scope.typeupdateFocus = $scope.nameupdateFocus = $scope.risktypeupdateFocus = $scope.elementkeyupdateFocus = function ($event, type) {
        verification(type, $event.target);
    };
    $scope.nextDisabled = function (myFormupdate) {
        return (myFormupdate.typeupdate.$pristine && myFormupdate.nameupdate.$pristine && myFormupdate.risktypeupdate.$pristine && myFormupdate.elementkeyupdate.$pristine && myFormupdate.status.$pristine) ||
            (!myFormupdate.typeupdate.$valid || !myFormupdate.nameupdate.$valid || !myFormupdate.risktypeupdate.$valid || !myFormupdate.elementkeyupdate.$valid || !myFormupdate.status.$valid);
    };
}

// 黑卡库管理
function riskBlackcardCtrl($scope, $timeout, $uibModal, httpSvc, NgTableParams, toaster) {
    // 获取参数
    httpSvc.getData('post', '/risk/getInit').then(function (value) {
            $scope.merchant = value.merchant;   // 商户信息
            $scope.siteurl = value.siteurl;     // 域名
            $scope.acquirer = value.acquirer;   // 收单机构
            $scope.limitConstant = value.limitConstant;    // 限制元素
            $scope.statusConstant = value.statusConstant;   // 状态
            $scope.init = value;   // 整个value对象
        }
    );
    // 显示表格数据
    $timeout(function () {
        $scope.$watch('init', function (newVal) {
            if (newVal !== undefined && newVal != null) {
                angular.element('.ibox-content').addClass('sk-loading');
                httpSvc.getData('post', '/risk/getBlackcard').then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    for (var i = 0; i < value.length; i++) {
                        // 限制元素
                        switch (value[i].element) {
                            case 'sys00000000101000003':
                                value[i]['elementName'] = '邮箱';
                                break;
                            case  'sys00000000101000002':
                                value[i]['elementName'] = '卡号';
                                break;
                            default:
                                break;
                        }
                        // 状态
                        switch (value[i].status) {
                            case 1:
                                value[i]['statusName'] = '启用';
                                break;
                            case 0:
                                value[i]['statusName'] = '禁用';
                                break;
                            default:
                                break;
                        }
                        // 名称、类型名称
                        switch (value[i].refType) {
                            case 0:
                                value[i]['refTypeName'] = '通用';
                                value[i]['refName'] = '通用';
                                break;
                            case 1:
                                // 收单机构名称
                                value[i]['refTypeName'] = '收单机构';
                                for (var j = 0; j < $scope.init.acquirer.length; j++) {
                                    value[i].refId += '';
                                    if (value[i].refId === $scope.init.acquirer[j].id) {
                                        value[i]['refName'] = $scope.init.acquirer[j].name;
                                        break;
                                    }
                                }
                                break;
                            case 2:
                                // 商户
                                value[i]['refTypeName'] = '商户';
                                for (var j = 0; j < $scope.init.merchant.length; j++) {
                                    if (value[i].refId === $scope.init.merchant[j].id) {
                                        value[i]['refName'] = $scope.init.merchant[j].name;
                                        break;
                                    }
                                }
                                break;
                            case 3:
                                // 域名
                                value[i]['refTypeName'] = '域名';
                                for (var j = 0; j < $scope.init.siteurl.length; j++) {
                                    if (value[i].refId === $scope.init.siteurl[j].id) {
                                        value[i]['refName'] = $scope.init.siteurl[j].siteUrl;
                                        break;
                                    }
                                }
                                break;
                            default:
                                break;
                        }
                    }
                    // 表格
                    $scope.BlackcardTable = new NgTableParams({}, {
                        dataset: value
                    });
                });
            }
        });
    });
    // 查询
    $scope.search = function (Blackcard) {
        angular.extend($scope.BlackcardTable.filter(), Blackcard);
    };
    // 重置
    $scope.resetForm = function () {
        $scope.Blackcard = {};
        $scope.BlackcardTable.filter({});
    };
    // 监听选项
    $scope.$watch('Blackcard.refTypeName', function (newVal) {
        switch (newVal) {
            case '通用':
                // $scope.initParam = [];
                $scope.Name = '通用';
                break;
            case '收单机构':
                //$scope.initParam = $scope.init.acquirer;
                $scope.Name = '';
                break;
            case '商户':
                //$scope.initParam = $scope.init.merchant;
                $scope.Name = '';
                break;
            case '域名':
                // $scope.initParam = $scope.init.siteurl;
                $scope.Name = '';
                break;
            default:
                // $scope.initParam = [];
                $scope.Name = '';
        }
    });
    // 启用与禁用操作
    $scope.locked = function ($event, row) {
        var locked_flag;
        angular.element($event.target).hasClass('active') ? locked_flag = 0 : locked_flag = 1;
        httpSvc.getData('post', '/risk/getblackcardLocked', {
            id: row.id,
            status: locked_flag
        }).then(function (value) {
            if (value === true) {
                toaster.pop({
                    type: 'success',
                    title: '黑卡库管理更新成功',
                    body: '更新状态成功'
                });
                angular.element($event.target).toggleClass('active');
                angular.element($event.target).toggleClass('btn-primary');
                angular.element($event.target).toggleClass('btn-danger');
                angular.element($event.target).hasClass('active') ?
                    angular.element($event.target).text('启用') :
                    angular.element($event.target).text('禁用');
                tableReload();
            } else {
                toaster.pop({
                    type: 'error',
                    title: '黑卡库管理更新失败',
                    body: '更新状态失败'
                });
            }
        })
    }
    // 面板注册
    $scope.showModal = function (risk, type) {
        var modalInstance = $uibModal.open({
            // 模板URL
            templateUrl: '/views/risk/risk_blackcard_modal',
            // 模板 Ctrl
            controller: 'riskBlackcardModalCtrl',
            // modal大小：lg
            // size:
            // 给modal传递参数
            resolve: {
                risk: function () {
                    return risk;
                },
                type: function () {
                    return type;
                },
                init: function () {
                    return $scope.init;
                }
            }
        });
        modalInstance.result.then(function () {
            // 点击关闭执行函数
            tableReload();
        }, function () {
            // 点击modal外部后关闭modal执行函数
            tableReload();
        });


    };
    // 面板额外点击事件
    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/risk/getBlackcard').then(function (value) {
            for (var i = 0; i < value.length; i++) {
                // 限制元素
                switch (value[i].element) {
                    case 'sys00000000101000003':
                        value[i]['elementName'] = '邮箱';
                        break;
                    case  'sys00000000101000002':
                        value[i]['elementName'] = '卡号';
                        break;
                    default:
                        break;
                }
                // 状态
                switch (value[i].status) {
                    case 1:
                        value[i]['statusName'] = '启用';
                        break;
                    case 0:
                        value[i]['statusName'] = '禁用';
                        break;
                    default:
                        break;
                }

                // 名称、类型名称
                switch (value[i].refType) {
                    case 0:
                        value[i]['refTypeName'] = '通用';
                        value[i]['refName'] = '通用';
                        break;
                    case 1:
                        // 收单机构名称
                        value[i]['refTypeName'] = '收单机构';
                        for (var j = 0; j < $scope.init.acquirer.length; j++) {
                            value[i].refId += '';
                            if (value[i].refId === $scope.init.acquirer[j].id) {
                                value[i]['refName'] = $scope.init.acquirer[j].name;
                                break;
                            }
                        }
                        break;
                    case 2:
                        // 商户
                        value[i]['refTypeName'] = '商户';
                        for (var j = 0; j < $scope.init.merchant.length; j++) {
                            if (value[i].refId === $scope.init.merchant[j].id) {
                                value[i]['refName'] = $scope.init.merchant[j].name;
                                break;
                            }
                        }
                        break;
                    case 3:
                        // 域名
                        value[i]['refTypeName'] = '域名';
                        for (var j = 0; j < $scope.init.siteurl.length; j++) {
                            if (value[i].refId === $scope.init.siteurl[j].id) {
                                value[i]['refName'] = $scope.init.siteurl[j].siteUrl;
                                break;
                            }
                        }
                        break;
                    default:
                        break;
                }
            }
            $scope.BlackcardTable.settings({
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
    // 批量删除操作
    var idArr = [];
    $scope.deleteFlag = true;
    $scope.collectSelectRows = function ($event, id) {
        var isChecked = angular.element($event.target).prop("checked");
        if (isChecked == true) {
            idArr.push(id);
            $scope.deleteFlag = false;
        } else if (isChecked == false) {
            idArr.pop(id);
            if (idArr === undefined || idArr.length == 0) {
                $scope.deleteFlag = true;
            } else {
                $scope.deleteFlag = false;
            }
        }
    }
    $scope.batchDel = function () {
        httpSvc.getData('post', '/risk/getblackcardBatchDel', idArr).then(function (value) {
            if (value > 0) {
                toaster.pop({
                    type: 'success',
                    title: '数据删除',
                    body: '删除成功！'
                });
                $scope.deleteFlag = true;
            } else {
                toaster.pop({
                    type: 'error',
                    title: '数据删除',
                    body: '删除失败！'
                });
                $scope.deleteFlag = true;
            }
            idArr = [];
            tableReload();
        });
    }
}

// 黑卡库管理的面板控制器
function riskBlackcardModalCtrl($scope, risk, type, toaster, httpSvc, $uibModalInstance, init) {
    $scope.risk = risk;
    if (risk !== undefined) {
        $scope.risk.refType = risk.refType + '';  // 隐式转换
        $scope.risk.refId = risk.refId + '';
        $scope.risk.status = risk.status + '';
    }
    $scope.type = type;
    $scope.init = init;
    //面板条件
    $scope.$watch('risk.refType', function (newVal) {
        switch (newVal) {
            case '0':
                $scope.initParam = [{id: 0, name: '通用'}];
                break;
            case '1':
                $scope.initParam = init.acquirer;
                break;
            case '2':
                $scope.initParam = init.merchant;
                break;
            case '3':
                $scope.initParam = init.siteurl;
                break;
            default:
                $scope.initParam = [];
        }
    });
    //关闭
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    // 新增操作
    $scope.insertblackCard = function (risk,type) {
        httpSvc.getData('post','/risk/getblackcardAddCount',risk).then(function (value) {
            if(value === 0){
                httpSvc.getData('post', '/risk/getblackcardAdd', risk).then(function (value) {
                    if(value === true) {
                        toaster.pop({
                            type: 'success',
                            title: '黑卡库管理添加成功',
                            body: '添加数据成功'
                        });
                        $uibModalInstance.dismiss();
                    }else{
                        toaster.pop(
                            {
                            type: 'error',
                            title: '黑卡库管理添加失败',
                            body: '添加数据失败'
                        });
                        $uibModalInstance.dismiss();
                    }
                });
            } else {
                toaster.pop({
                   type: 'error',
                   title: '不符合风控规则',
                   body: '添加数据失败'
                });
                $uibModalInstance.dismiss();
            }
        });
    };
    // 更新操作
    $scope.updateblackCard = function (risk, type) {
        httpSvc.getData('post', '/risk/getblackcardUpdate', risk).then(function (value) {
            if (value === true) {
                toaster.pop({
                    type: 'success',
                    title: '黑卡库管理更新成功',
                    body: '更新数据成功'
                });
            } else {
                toaster.pop({
                    type: 'error',
                    title: '黑卡库管理更新失败',
                    body: '更新数据失败'
                });
            }
            $uibModalInstance.dismiss();
        });
    };
    // 面板操作
    $scope.typeBlur = $scope.nameBlur = $scope.elementBlur = $scope.elementValueBlur = $scope.statusBlur = function ($event, type) {
        verification(type, $event.target);
    };
    $scope.typeupdateFocus = $scope.nameupdateFocus = $scope.elementupdateFocus = $scope.elementValueupdateFocus = $scope.statusupdateBlur = function ($event, type) {
        verification(type, $event.target);
    };
    $scope.nextDisabled = function (myFormupdate) {
        return (myFormupdate.typeupdate.$pristine && myFormupdate.nameupdate.$pristine && myFormupdate.elementupdate.$pristine && myFormupdate.elementValueupdate.$pristine && myFormupdate.statusupdate.$pristine) ||
            (!myFormupdate.typeupdate.$valid || !myFormupdate.nameupdate.$valid || !myFormupdate.elementupdate.$valid || !myFormupdate.elementValueupdate.$valid || !myFormupdate.statusupdate.$valid);
    };
}

// 商务卡管理
function riskBusinessCtrl($scope, $timeout, $uibModal, httpSvc, NgTableParams, toaster) {
    // 全部参数获取
    httpSvc.getData('post', '/risk/getInit').then(function (value) {
            $scope.credit = value.credit; // 信用卡支付
            $scope.init = value;   // 整个value对象
        }
    );
    // 查询
    $scope.search = function (Business) {
        angular.extend($scope.BusinessTable.filter(), Business);
    };
    // 重置
    $scope.resetForm = function () {
        $scope.Business = {};
        $scope.BusinessTable.filter({});
    };
    // 下拉框数据
    $timeout(function () {
        $scope.$watch('init', function (newVal) {
            if (newVal !== undefined && newVal != null) {
                angular.element('.ibox-content').addClass('sk-loading');
                httpSvc.getData('post', '/risk/getBusiness').then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    for (var i = 0; i < value.length; i++) {
                        // 信用卡
                        for (var j = 0; j < $scope.init.credit.length; j++) {
                            if (value[i].payType === $scope.init.credit[j].firstValue) {
                                value[i]['refcreditName'] = $scope.init.credit[j].name;
                                break;
                            }
                        }

                    }
                    // 表格
                    $scope.BusinessTable = new NgTableParams({}, {
                        dataset: value
                    });
                });
            }
        });
    });
    // type：0为添加,1为更新,2为删除
    $scope.showModal = function (risk, type) {
        var modalInstance = $uibModal.open({
            // 模板URL
            templateUrl: '/views/risk/risk_business_modal',
            // 模板 Ctrl
            controller: 'riskBusinessModalCtrl',
            // modal大小：lg
            // size:
            // 给modal传递参数
            resolve: {
                risk: function () {
                    return risk;
                },
                type: function () {
                    return type;
                },
                init: function () {
                    return $scope.init;
                }
            }
        });
        modalInstance.result.then(function () {
            // 点击关闭执行函数
            tableReload();
        }, function () {
            // 点击modal外部后关闭modal执行函数
            tableReload();
        });


    };
    // 弹窗的额外点击事件
    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/risk/getBusiness').then(function (value) {
            for (var i = 0; i < value.length; i++) {
                // 信用卡
                for (var j = 0; j < $scope.init.credit.length; j++) {
                    if (value[i].payType === $scope.init.credit[j].firstValue) {
                        value[i]['refcreditName'] = $scope.init.credit[j].name;
                        break;
                    }
                }
            }
            $scope.BusinessTable.settings({
                dataset: value
            });
            $scope.totalItems = value.length;
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
    // 商务卡批量删除操作
    var idArr = [];
    $scope.deleteFlag = true;
    $scope.collectSelectRows = function ($event, id) {
        var isChecked = angular.element($event.target).prop("checked");
        if (isChecked == true) {
            idArr.push(id);
            $scope.deleteFlag = false;
        } else if (isChecked == false) {
            idArr.pop(id);
            if (idArr === undefined || idArr.length == 0) {
                $scope.deleteFlag = true;
            } else {
                $scope.deleteFlag = false;
            }
        }
    }
    $scope.batchDel = function () {
        httpSvc.getData('post', '/risk/getbusinessBatchDel', idArr).then(function (value) {
            if (value > 0) {
                toaster.pop({
                    type: 'success',
                    title: '数据删除',
                    body: '删除成功！'
                });
                $scope.deleteFlag = true;
            } else {
                toaster.pop({
                    type: 'error',
                    title: '数据删除',
                    body: '删除失败！'
                });
                $scope.deleteFlag = true;
            }
            idArr = [];
            tableReload();
        });
    }
}

// 商务卡管理的面板控制器
function riskBusinessModalCtrl($scope, risk, type, toaster, httpSvc, $uibModalInstance, init) {
    $scope.risk = risk;
    $scope.type = type;
    $scope.init = init;
    // 关闭
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    // 新增操作
    $scope.insertRiskBusiness = function (risk,type) {
        httpSvc.getData('post','/risk/getbusinessAddCount',risk).then(function (value) {
            if (value === 0){
                httpSvc.getData('post', '/risk/getbusinessAdd', risk).then(function (value) {
                    if(value === true) {
                        toaster.pop({
                            type: 'success',
                            title: '商务卡管理添加成功',
                            body: '添加数据成功'
                        });
                    }else{
                        toaster.pop({
                            type: 'error',
                            title: '商务卡管理添加失败',
                            body: '添加数据失败'
                        });
                    }
                    $uibModalInstance.dismiss();
                });
            } else {
                toaster.pop({
                    type:  'error',
                    title: '不符合风控规则',
                    body: '添加数据失败'
                });
                $uibModalInstance.dismiss();
            }
        });
    }
    // 更新操作
    $scope.updateRiskBusiness = function (risk, type) {
        httpSvc.getData('post', '/risk/getbusinessUpdate', risk).then(function (value) {
            if (value === true) {
                toaster.pop({
                    type: 'success',
                    title: '商务卡管理更新成功',
                    body: '更新数据成功'
                });
            } else {
                toaster.pop({
                    type: 'error',
                    title: '商务卡管理更新失败',
                    body: '更新数据失败'
                });
            }
            $uibModalInstance.dismiss();
        });
    };
    // 面板验证操作
    $scope.typeBlur = $scope.startnumberBlur = $scope.finallnumberBlur = function ($event, type) {
        verification(type, $event.target);
    };
    $scope.typeupdateFocus = $scope.startnumberupdateFocus = $scope.finallnumberupdateFocus = function ($event, type) {
        verification(type, $event.target);
    };
    $scope.nextDisabled = function (myFormupdate) {
        return (myFormupdate.typeupdate.$pristine && myFormupdate.startnumberupdate.$pristine && myFormupdate.finallnumberupdate.$pristine) ||
            (!myFormupdate.typeupdate.$valid || !myFormupdate.startnumberupdate.$valid || !myFormupdate.finallnumberupdate.$valid);
    };
}

// 发卡行管理
function riskIssuerCtrl($scope, $timeout, $uibModal, httpSvc, NgTableParams, toaster) {
    // 全部参数的获取
    httpSvc.getData('post', '/risk/getInit').then(function (value) {
        $scope.country = value.country; // 国家
        $scope.init = value; // 整个value对象
    });
    // 表格的数据显示
    $timeout(function () {
        $scope.$watch('init', function (newVal) {
            if (newVal !== undefined && newVal != null) {
                angular.element('.ibox-content').addClass('sk-loading');
                httpSvc.getData('post', '/risk/getIssuer').then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    for (var i = 0; i < value.length; i++) {
                        // 国家
                        for (var j = 0; j < $scope.init.country.length; j++) {
                            if (value[i].country === $scope.init.country[j].firstValue) {
                                value[i]['refcountryName'] = $scope.init.country[j].name;
                                break;
                            }
                        }

                    }
                    // 表格
                    $scope.IssuerTable = new NgTableParams({}, {
                        dataset: value
                    });
                });
            }
        });
    });
    // 查询
    $scope.search = function (Issuer) {
        angular.extend($scope.IssuerTable.filter(), Issuer);
    };
    // 重置
    $scope.resetForm = function () {
        $scope.Issuer = {};
        $scope.IssuerTable.filter({});
    };
    // 弹窗注册
    $scope.showModal = function (risk, type) {
        var modalInstance = $uibModal.open({
            // 模板URL
            templateUrl: '/views/risk/risk_issuers_modal',
            // 模板 Ctrl
            controller: 'riskIssuerModalCtrl',
            // modal大小：lg
            // size:
            // 给modal传递参数
            resolve: {
                risk: function () {
                    return risk;
                },
                type: function () {
                    return type;
                },
                init: function () {
                    return $scope.init;
                }
            }
        });
        modalInstance.result.then(function () {
            // 点击关闭执行函数
            tableReload();
        }, function () {
            // 点击modal外部后关闭modal执行函数
            tableReload();
        });
    };

    // 弹窗额外事件
    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/risk/getIssuer').then(function (value) {
            for (var i = 0; i < value.length; i++) {
                // 国家
                for (var j = 0; j < $scope.init.country.length; j++) {
                    if (value[i].country === $scope.init.country[j].firstValue) {
                        value[i]['refcountryName'] = $scope.init.country[j].name;
                        break;
                    }
                }

            }
            $scope.IssuerTable.settings({
                dataset: value
            });
            $scope.totalItems = value.length;
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }

    // 商务卡批量删除操作
    var idArr = [];
    $scope.deleteFlag = true;
    $scope.collectSelectRows = function ($event, id) {
        var isChecked = angular.element($event.target).prop("checked");
        if (isChecked == true) {
            idArr.push(id);
            $scope.deleteFlag = false;
        } else if (isChecked == false) {
            idArr.pop(id);
            if (idArr === undefined || idArr.length == 0) {
                $scope.deleteFlag = true;
            } else {
                $scope.deleteFlag = false;
            }
        }
    }
    $scope.batchDel = function () {
        httpSvc.getData('post', '/risk/getissuerBatchDel', idArr).then(function (value) {
            if (value > 0) {
                toaster.pop({
                    type: 'success',
                    title: '数据删除',
                    body: '删除成功！'
                });
                $scope.deleteFlag = true;
            } else {
                toaster.pop({
                    type: 'error',
                    title: '数据删除',
                    body: '删除失败！'
                });
                $scope.deleteFlag = true;
            }
            idArr = [];
            tableReload();
        });
    }
}

// 发卡行管理的面板控制器
function riskIssuerModalCtrl($scope, risk, type, toaster, httpSvc, $uibModalInstance, init) {
    $scope.risk = risk;
    $scope.type = type;
    $scope.init = init;
    // 关闭
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    // 新增操作
    $scope.insertRiskIssuer = function (risk,type) {
        httpSvc.getData('post','/risk/getissuerAddCount',risk).then(function (value) {
            if(value === 0){
                httpSvc.getData('post', '/risk/getissuerAdd', risk).then(function (value) {
                    if(value === true) {
                        toaster.pop({
                            type: 'success',
                            title: '发卡行管理添加成功',
                            body: '添加数据成功'
                        });
                    }else{
                        toaster.pop({
                            type: 'error',
                            title: '发卡行管理添加失败',
                            body: '添加数据失败'
                        });
                    }
                    $uibModalInstance.dismiss();
                });
            }else {
                toaster.pop({
                    type: 'error',
                    title: '不符合风控规则',
                    body: '添加数据失败'
                });
                $uibModalInstance.dismiss();
            }
        });
    }
    // 更新操作
    $scope.updateRiskIssuer = function (risk, type) {
        httpSvc.getData('post', '/risk/getissuerUpdate', risk).then(function (value) {
            if (value === true) {
                toaster.pop({
                    type: 'success',
                    title: '发卡行管理更新成功',
                    body: '更新数据成功'
                });
            } else {
                toaster.pop({
                    type: 'error',
                    title: '发卡行管理更新失败',
                    body: '更新数据失败'
                });
            }
            $uibModalInstance.dismiss();
        });
    };
    // 面板验证操作
    $scope.nameBlur = $scope.countryBlur = $scope.phoneBlur = function ($event, type) {
        verification(type, $event.target);
    };
    $scope.nameupdateFocus = $scope.countryupdateFocus = $scope.phoneupdateFocus = function ($event, type) {
        verification(type, $event.target);
    };
    $scope.nextDisabled = function (myFormupdate) {
        return (myFormupdate.nameupdate.$pristine && myFormupdate.countryupdate.$pristine && myFormupdate.phoneupdate.$pristine) ||
            (!myFormupdate.nameupdate.$valid || !myFormupdate.countryupdate.$valid || !myFormupdate.phoneupdate.$valid);
    };
}

// 异常订单管理
function operationAbnormalCtrl($scope, $timeout, $filter, $uibModal, httpSvc, NgTableParams) {
    $scope.merchantinfo = [];
    $scope.orderTypeTxt = '平台订单号';
    $scope.orderType = 'orderId';
    $scope.minText = 3;
    $scope.init = null;
    var merWeb = [];
    var searchInfo = null;
    //选择平台订单号,商户订单号,银行流水号
    $scope.orderSwitch = function ($event, orderType) {
        $scope.orderTypeTxt = angular.element($event.target).text();
        $scope.orderType = orderType;
    };
    //获取下拉框数据
    httpSvc.getData('post', '/operation/getInit').then(function (value) {
        $scope.merchants = value.merchant; // 商户
        $scope.siteUrls = value.siteurl; // 域名
        $scope.exceptionstatus = value.exceptionstatus; // 异常状态
        $scope.init = value; // 整个value对象
        $scope.AbnormalTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/operation/getAbnormal', {
                    pageFirst: params.page() - 1,
                    pageSize: params.count()
                }).then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    params.total(value[value.length - 1].result);
                    for (var i = 0; i < value.length; i++) {
                        switch (value[i].type) {
                            case 1:
                                value[i]['typeName'] = '冻结';
                                break;
                            case 2:
                                value[i]['typeName'] = '全额退款';
                                break;
                            case 3:
                                value[i]['typeName'] = '部分退款';
                                break;
                            case 4:
                                value[i]['typeName'] = '全额拒付';
                                break;
                            case 5:
                                value[i]['typeName'] = '部分拒付';
                                break;
                            case 6:
                                value[i]['typeName'] = '代理拒付';
                                break;
                            case 7:
                                value[i]['typeName'] = '银行处理退款中';
                                break;
                            default:
                                break;
                        }
                        switch (value[i].status) {
                            case 0:
                                value[i]['statusName'] = '未审核';
                                break;
                            case 1:
                                value[i]['statusName'] = '已通过';
                                break;
                            case 2:
                                value[i]['statusName'] = '未通过';
                                break;
                            case 3:
                                value[i]['statusName'] = '银行处理中';
                                break;
                            default:
                                break;
                        }
                    }
                    return value.slice(0, value.length - 1);
                });
            }
        });
    });
    //下拉框显示数据
    $timeout(function () {
        // 域名
        $scope.$watch('selectedMerchant', function (newVal) {
            if (newVal !== undefined) {
                merWeb = [];
                var input = newVal.title;
                for (var i = 0, j = $scope.init.siteurl.length; i < j; i++) {
                    if ($scope.init.siteurl[i].merId === Number(input)) {
                        merWeb.push($scope.init.siteurl[i]);
                    }
                }
                $scope.siteUrls = merWeb;
                $scope.minText = 0;
                $scope.webDisable = false;
            } else {
                $scope.minText = 3;
                if ($scope.siteUrls !== undefined) {
                    $scope.siteUrls = $scope.init.siteurl;
                }
                merWeb = [];
            }
        });
        // 申请日期
        $scope.$watch('auditBeginDate', function (newVal) {
            if (newVal !== '' && newVal !== undefined && newVal != null) {
                $scope.dateOptions2.minDate = $scope.auditBeginDate;
                $scope.auditEndDateDisable = false;
                if (oldEndDate !== '') {
                    $scope.auditBeginDate = oldEndDate;
                }
            } else {
                $scope.auditEndDateDisable = true;
                oldEndDate = $scope.auditBeginDate;
                $scope.auditBeginDate = '';
            }
        });
        // 审核日期
        $scope.$watch('BeginDate', function (newVal) {
            if (newVal !== '' && newVal !== undefined && newVal != null) {
                $scope.dateOptions4.minDate = $scope.BeginDate;
                $scope.EndDateDisable = false;
                if (oldEndDateCheck !== '') {
                    $scope.BeginDate = oldEndDateCheck;
                }
            } else {
                $scope.EndDateDisable = true;
                oldEndDateCheck = $scope.BeginDate;
                $scope.BeginDate = '';
            }
        });
    });
    //申请日期
    var oldEndDate = '';
    $scope.auditEndDateDisable = true;
    $scope.format = 'yyyy/MM/dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    // 审核日期
    var oldEndDateCheck = '';
    $scope.EndDateDisable = true;
    $scope.format = 'yyyy/MM/dd';
    $scope.dateOptions3 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions4 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup3 = {
        opend: false
    };
    $scope.openDatepicker3 = function () {
        $scope.popup3.opend = !$scope.popup3.opend;
    };
    $scope.popup4 = {
        opend: false
    };
    $scope.openDatepicker4 = function () {
        $scope.popup4.opend = !$scope.popup4.opend;
    };
    // 查询
    $scope.searchAbnormal = function (searchInfo) {
        if (searchInfo !== undefined && searchInfo != null) {
            httpSvc.getData('post', '/operation/getAbnormalCheck', searchInfo).then(function (value) {
                for (var i = 0; i < value.length; i++) {
                    // 类型
                    switch (value[i].type) {
                        case 1:
                            value[i]['typeName'] = '冻结';
                            break;
                        case 2:
                            value[i]['typeName'] = '全额退款';
                            break;
                        case 3:
                            value[i]['typeName'] = '部分退款';
                            break;
                        case 4:
                            value[i]['typeName'] = '全额拒付';
                            break;
                        case 5:
                            value[i]['typeName'] = '部分拒付';
                            break;
                        case 6:
                            value[i]['typeName'] = '代理拒付';
                            break;
                        case 7:
                            value[i]['typeName'] = '银行处理退款中';
                            break;
                        default:
                            break;
                    }
                    // 状态
                    switch (value[i].status) {
                        case 0:
                            value[i]['statusName'] = '未审核';
                            break;
                        case 1:
                            value[i]['statusName'] = '已通过';
                            break;
                        case 2:
                            value[i]['statusName'] = '未通过';
                            break;
                        case 3:
                            value[i]['statusName'] = '银行处理中';
                            break;
                        default:
                            break;
                    }
                }
                // 表格
                $scope.AbnormalTable = new NgTableParams({}, {
                    dataset: value
                });
            });
        } else {
            $scope.AbnormalTable = new NgTableParams({}, {
                getData: function (params) {
                    angular.element('.ibox-content').addClass('sk-loading');
                    return httpSvc.getData('post', '/operation/getAbnormal', {
                        pageFirst: params.page() - 1,
                        pageSize: params.count()
                    }).then(function (value) {
                        angular.element('.ibox-content').removeClass('sk-loading');
                        params.total(value[value.length - 1].result);
                        for (var i = 0; i < value.length; i++) {
                            switch (value[i].type) {
                                case 1:
                                    value[i]['typeName'] = '冻结';
                                    break;
                                case 2:
                                    value[i]['typeName'] = '全额退款';
                                    break;
                                case 3:
                                    value[i]['typeName'] = '部分退款';
                                    break;
                                case 4:
                                    value[i]['typeName'] = '全额拒付';
                                    break;
                                case 5:
                                    value[i]['typeName'] = '部分拒付';
                                    break;
                                case 6:
                                    value[i]['typeName'] = '代理拒付';
                                    break;
                                case 7:
                                    value[i]['typeName'] = '银行处理退款中';
                                    break;
                                default:
                                    break;
                            }
                            switch (value[i].status) {
                                case 0:
                                    value[i]['statusName'] = '未审核';
                                    break;
                                case 1:
                                    value[i]['statusName'] = '已通过';
                                    break;
                                case 2:
                                    value[i]['statusName'] = '未通过';
                                    break;
                                case 3:
                                    value[i]['statusName'] = '银行处理中';
                                    break;
                                default:
                                    break;
                            }
                        }
                        return value.slice(0, value.length - 1);
                    });
                }
            });
        }
    };
    // 重置
    $scope.resetForm = function () {
        $scope.searchInfo = null;
        angular.element('#orderId').val('');
        angular.element('#merId').val('');
        angular.element('#siteId').val('');
        angular.element('#accountId').val('');
        angular.element('#applicant').val('');
        angular.element('#auditBeginDate').val('');
        angular.element('#auditEndDate').val('');
        angular.element('#exceptionstatus').val('');
        angular.element('#BeginDate').val('');
        angular.element('#EndDate').val('');
        angular.element('#reviewer').val('');
        angular.element('#reviewerfinall').val('');
        $scope.dateOptions1 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.dateOptions2 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.dateOptions3 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.dateOptions4 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.$broadcast('angucomplete-alt:clearInput');
        $scope.AbnormalTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/operation/getAbnormal', {
                    pageFirst: params.page() - 1,
                    pageSize: params.count()
                }).then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    params.total(value[value.length - 1].result);
                    for (var i = 0; i < value.length; i++) {
                        switch (value[i].type) {
                            case 1:
                                value[i]['typeName'] = '冻结';
                                break;
                            case 2:
                                value[i]['typeName'] = '全额退款';
                                break;
                            case 3:
                                value[i]['typeName'] = '部分退款';
                                break;
                            case 4:
                                value[i]['typeName'] = '全额拒付';
                                break;
                            case 5:
                                value[i]['typeName'] = '部分拒付';
                                break;
                            case 6:
                                value[i]['typeName'] = '代理拒付';
                                break;
                            case 7:
                                value[i]['typeName'] = '银行处理退款中';
                                break;
                            default:
                                break;
                        }
                        switch (value[i].status) {
                            case 0:
                                value[i]['statusName'] = '未审核';
                                break;
                            case 1:
                                value[i]['statusName'] = '已通过';
                                break;
                            case 2:
                                value[i]['statusName'] = '未通过';
                                break;
                            case 3:
                                value[i]['statusName'] = '银行处理中';
                                break;
                            default:
                                break;
                        }
                    }
                    return value.slice(0, value.length - 1);
                });
            }
        });
    };
    // 弹窗注册
    $scope.showModal = function (row) {
        var modalInstance = $uibModal.open({
            // 模板URL
            templateUrl: '/views/operation/operation_abnormal_modal',
            // 模板Ctrl
            controller: 'operationAbnormalModalCtrl',
            resolve: {
                row: function () {
                    return row;
                },
                init: function () {
                    return $scope.init;
                }
            }

        });
        modalInstance.result.then(function () {
            // 点击关闭执行函数
            tableReload();
        }, function () {
            // 点击modal外部后关闭modal执行函数
            tableReload();
        });
    };
    // 弹窗额外事件
    function tableReload() {
        $scope.AbnormalTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/operation/getAbnormal', {
                    pageFirst: params.page() - 1,
                    pageSize: params.count()
                }).then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    params.total(value[value.length - 1].result);
                    for (var i = 0; i < value.length; i++) {
                        switch (value[i].type) {
                            case 1:
                                value[i]['typeName'] = '冻结';
                                break;
                            case 2:
                                value[i]['typeName'] = '全额退款';
                                break;
                            case 3:
                                value[i]['typeName'] = '部分退款';
                                break;
                            case 4:
                                value[i]['typeName'] = '全额拒付';
                                break;
                            case 5:
                                value[i]['typeName'] = '部分拒付';
                                break;
                            case 6:
                                value[i]['typeName'] = '代理拒付';
                                break;
                            case 7:
                                value[i]['typeName'] = '银行处理退款中';
                                break;
                            default:
                                break;
                        }
                        switch (value[i].status) {
                            case 0:
                                value[i]['statusName'] = '未审核';
                                break;
                            case 1:
                                value[i]['statusName'] = '已通过';
                                break;
                            case 2:
                                value[i]['statusName'] = '未通过';
                                break;
                            case 3:
                                value[i]['statusName'] = '银行处理中';
                                break;
                            default:
                                break;
                        }
                    }
                    return value.slice(0, value.length - 1);
                });
            }
        });
    }
}

// 异常订单管理的面板控制器
function operationAbnormalModalCtrl($scope, row, toaster, httpSvc, $uibModalInstance, init) {
    $scope.row = row;
    $scope.init = init;
    $scope.row.status = 1;
    // 隐式转换
    $scope.row.status += '';
    // 关闭
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    // 审核操作
    $scope.auditAbnormal = function (row) {
        httpSvc.getData('post', '/operation/getAbnormalAudit', row).then(function (value) {
            if (value.code === 1) {
                toaster.pop({
                    type: 'success',
                    title: '退款成功',
                    body: '退款成功'
                });
            }else if (value.code === 2) {
                toaster.pop({
                    type: 'error',
                    title: '银行拒绝退款',
                    body: '银行拒绝退款'
                });
            }else if (value.code === 3) {
                toaster.pop({
                    type: 'error',
                    title: '银行超时请求',
                    body: '银行超时请求'
                });
            } else if (value.code === 4) {
                toaster.pop({
                    type: 'success',
                    title: '退款申请成功',
                    body: '退款申请成功'
                });
            } else if (value.code === 5) {
                toaster.pop({
                    type: 'error',
                    title: '退款申请失败',
                    body: '退款申请失败'
                });
            }else if (value.code === 6) {
                toaster.pop({
                    type: 'success',
                    title: '拒付成功',
                    body: '拒付成功'
                });
            }else if (value.code === 7) {
                toaster.pop({
                    type: 'error',
                    title: '拒付失败',
                    body: '拒付失败'
                });
            }else {
                toaster.pop({
                    type: 'error',
                    title: '审核未通过',
                    body: '审核未通过'
                });
            }
            $uibModalInstance.dismiss();
        });
    }

}

// 提现审核管理
function operationWithdrawalCtrl($scope, $timeout, $filter, $uibModal, $stateParams, httpSvc, toaster, NgTableParams) {

    var type = $stateParams.type;
    $scope.currentType = $stateParams.type;
    $scope.init = null;
    $scope.searchInfo = {};
    // 获取下拉框数据
    httpSvc.getData('post', '/operation/getInit').then(function (value) {
        $scope.merchant = value.merchant;  // 商户
        $scope.init = value;  // 整个value
        $scope.WithdrawalTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/operation/getWithdrawal', {
                    pageFirst: (params.page() - 1) * 10,
                    pageSize: params.count(),
                    status: type
                }).then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    params.total(value[value.length - 1].result);
                    for (var i = 0; i < value.length; i++) {
                        // 状态
                        switch (value[i].status) {
                            case 0:
                                value[i]['statusName'] = '无效';
                                break;
                            case 1:
                                value[i]['statusName'] = '待审核';
                                break;
                            case 2:
                                value[i]['statusName'] = '待划款';
                                break;
                            case 3:
                                value[i]['statusName'] = '已划款';
                                break;
                            case 4:
                                value[i]['statusName'] = '自动扣款';
                                break;
                            case 5:
                                value[i]['statusName'] = '待复核';
                                break;
                            default:
                                break;
                        }
                        // 实际划款金额
                        if (value[i].real_amount == null) {
                            value[i]['real_amount_status'] = "无";
                        } else {
                            value[i]['real_amount_status'] = value[i].real_amount;
                        }
                    }
                    return value.slice(0, value.length - 1);
                });
            }
        });
    });
    elementControl(type);
    // 下拉框显示数据
    $timeout(function () {
        // 审核日期
        $scope.$watch('searchInfo.auditBeginDate', function (newVal) {
            if (newVal !== '' && newVal !== undefined && newVal != null) {
                $scope.dateOptions2.minDate = $scope.auditBeginDate;
                $scope.auditEndDateDisable = false;
                if (oldEndDate !== '') {
                    $scope.auditBeginDate = oldEndDate;
                }
            } else {
                $scope.auditEndDateDisable = true;
                oldEndDate = $scope.auditBeginDate;
                $scope.auditBeginDate = '';
            }
        });
        //申请时间
        $scope.$watch('searchInfo.applyTime', function (newVal) {
            if (newVal !== '' && newVal !== undefined && newVal != null) {
                $scope.dateOptions2.minDate = $scope.applyTime;
                $scope.applyOverTimeDisable = false;
                if (oldEndDate !== '') {
                    $scope.applyTime = oldEndDate;
                }
            } else {
                $scope.applyOverTimeDisable = true;
                oldEndDate = $scope.applyTime;
                $scope.applyTime = '';
            }
        });
    });
    $scope.$watch('selectedMerchant', function (newVal) {

        if (newVal !== undefined) {

            $scope.searchInfo.merId = newVal.originalObject.id;

        }
    });
    // 申请日期
    var oldEndDate = '';
    $scope.auditEndDateDisable = true;
    $scope.format = 'yyyy/MM/dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    $scope.popup3 = {

        opend: false
    };
    $scope.openDatepicker3 = function () {

        $scope.popup3.opend = !$scope.popup3.opend;
    };
    $scope.popup4 = {

        opend: false
    };
    $scope.openDatepicker4 = function () {

        $scope.popup4.opend = !$scope.popup4.opend;
    };

    // 查询
    $scope.searchWithdrawal = function (data) {
        $scope.searchInfo = data;
        if ($scope.searchInfo !== undefined && $scope.searchInfo != null) {
            $scope.searchInfo['status'] = type;
            angular.element('.ibox-content').addClass('sk-loading');
            httpSvc.getData('post', '/operation/getWithdrawalCheck', $scope.searchInfo).then(function (value) {
                angular.element('.ibox-content').removeClass('sk-loading');
                for (var i = 0; i < value.length; i++) {
                    // 状态
                    switch (value[i].status) {
                        case 0:
                            value[i]['statusName'] = '无效';
                            break;
                        case 1:
                            value[i]['statusName'] = '待审核';
                            break;
                        case 2:
                            value[i]['statusName'] = '待划款';
                            break;
                        case 3:
                            value[i]['statusName'] = '已划款';
                            break;
                        case 4:
                            value[i]['statusName'] = '自动扣款';
                        case 5:
                            value[i]['statusName'] = '待复核';
                            break;
                        default:
                            break;
                    }
                    // 实际划款金额
                    if (value[i].realAmount == null) {
                        value[i]['real_amount_status'] = "无";
                    } else {
                        value[i]['real_amount_status'] = value[i].realAmount;
                    }
                }
                // 表格
                $scope.WithdrawalTable = new NgTableParams({}, {
                    dataset: value
                });
            });
        } else {
            $scope.WithdrawalTable = new NgTableParams({}, {
                getData: function (params) {
                    angular.element('.ibox-content').addClass('sk-loading');
                    return httpSvc.getData('post', '/operation/getWithdrawal', {
                        pageFirst: (params.page() - 1) * 10,
                        pageSize: params.count(),
                        status: type
                    }).then(function (value) {
                        angular.element('.ibox-content').removeClass('sk-loading');
                        params.total(value[value.length - 1].result);
                        for (var i = 0; i < value.length; i++) {
                            // 状态
                            switch (value[i].status) {
                                case 0:
                                    value[i]['statusName'] = '无效';
                                    break;
                                case 1:
                                    value[i]['statusName'] = '待审核';
                                    break;
                                case 2:
                                    value[i]['statusName'] = '待划款';
                                    break;
                                case 3:
                                    value[i]['statusName'] = '已划款';
                                    break;
                                case 4:
                                    value[i]['statusName'] = '自动扣款';
                                    break;
                                case 5:
                                    value[i]['statusName'] = '待复核';
                                    break;
                                default:
                                    break;
                            }
                            // 实际划款金额
                            if (value[i].real_amount == null) {
                                value[i]['real_amount_status'] = "无";
                            } else {
                                value[i]['real_amount_status'] = value[i].real_amount;
                            }
                        }
                        return value.slice(0, value.length - 1);
                    });
                }
            });
        }
    };
    // 重置
    $scope.resetForm = function () {
        $scope.searchInfo = {};
        angular.element('#merId').val('');
        angular.element('#applicant').val('');
        angular.element('#auditBeginDate').val('');
        angular.element('#auditEndDate').val('');
        angular.element('#reviewer').val('');
        angular.element('#transfer').val('');
        angular.element('#reviewerfinall').val('');
        $scope.dateOptions1 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.dateOptions2 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.$broadcast('angucomplete-alt:clearInput');
        $scope.WithdrawalTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/operation/getWithdrawal', {
                    pageFirst: params.page() - 1,
                    pageSize: params.count(),
                    status: type
                }).then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    params.total(value[value.length - 1].result);
                    for (var i = 0; i < value.length; i++) {
                        // 状态
                        switch (value[i].status) {
                            case 0:
                                value[i]['statusName'] = '无效';
                                break;
                            case 1:
                                value[i]['statusName'] = '待审核';
                                break;
                            case 2:
                                value[i]['statusName'] = '待划款';
                                break;
                            case 3:
                                value[i]['statusName'] = '已划款';
                                break;
                            case 4:
                                value[i]['statusName'] = '自动扣款';
                                break;
                            case 5:
                                value[i]['statusName'] = '待复核';
                                break;
                            default:
                                break;
                        }
                        // 实际划款金额
                        if (value[i].real_amount == null) {
                            value[i]['real_amount_status'] = "无";
                        } else {
                            value[i]['real_amount_status'] = value[i].real_amount;
                        }
                    }
                    return value.slice(0, value.length - 1);
                });
            }
        });
    };
    // 弹窗注册
    $scope.showModal = function (row) {
        var modalInstance = $uibModal.open({
            // 模板url
            templateUrl: '/views/operation/operation_withdrawal_modal',
            // 模板Ctrl
            controller: 'operationWithdrawalModalCtrl',
            resolve: {
                row: function () {
                    return row;
                },

                init: function () {
                    return $scope.init;
                }
            }
        });
        modalInstance.result.then(function () {
            // 点击关闭执行函数
            tableReload();
        }, function () {
            // 点击modal外部后关闭modal执行函数
            tableReload();
        });
    };

    // 弹窗额外事件
    function tableReload() {
        $scope.WithdrawalTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/operation/getWithdrawal', {
                    pageFirst: params.page() - 1,
                    pageSize: params.count(),
                    status: type
                }).then(function (value) {
                    angular.element('.ibox-content').removeClass('sk-loading');
                    params.total(value[value.length - 1].result);
                    for (var i = 0; i < value.length; i++) {
                        // 状态
                        switch (value[i].status) {
                            case 0:
                                value[i]['statusName'] = '无效';
                                break;
                            case 1:
                                value[i]['statusName'] = '待审核';
                                break;
                            case 2:
                                value[i]['statusName'] = '待划款';
                                break;
                            case 3:
                                value[i]['statusName'] = '已划款';
                                break;
                            case 4:
                                value[i]['statusName'] = '自动扣款';
                                break;
                            case 5:
                                value[i]['statusName'] = '待复核';
                                break;
                            default:
                                break;
                        }
                        // 实际划款金额
                        if (value[i].real_amount == null) {
                            value[i]['real_amount_status'] = "无";
                        } else {
                            value[i]['real_amount_status'] = value[i].real_amount;
                        }
                    }
                    return value.slice(0, value.length - 1);
                });
            }
        });
    };

    //针对"复核处理"和"划款"做状态校验 隐藏不必要的元素
    function elementControl(type) {

        switch (type) {

            case "1"://提现审核

                $scope.isTitle = "WITHDRAWAL";
                break;

            case "2": //划款

                $scope.isTitle = 'TRANSFER_MONEY';
                $scope.isShow = true;
                $scope.isShowReviewRemark = true;

                break;

            case "5":  //复核处理

                $scope.isTitle = "WITHDRAWAL_PROCESSING";
                $scope.isShow = true;
                $scope.isShowAuditRemark = true;
                break;

        }

    }

    //打印
    $scope.printForm = function () {

        if ("" == $scope.searchInfo.merId || undefined == $scope.searchInfo.merId || null == $scope.searchInfo.merId) {
            toaster.pop({
                type: 'error',
                title: '打印失败',
                body: '请输入商户号!'
            });
            return;
        }

        httpSvc.getData('post', '/operation/getreviewPrintData', $scope.searchInfo).then(function (value) {
            if (value.length > 5) {
                toaster.pop({
                    type: 'error',
                    title: '打印失败',
                    body: '划款记录条数，超过5条!'
                });
                return;
            }
            $scope.total = 0;  //计算小计
            for (var i = 0; i < value.length; i++) {
                $scope.total += value[i].amount;
            }
            $scope.amountWords = digitUppercase($scope.total); //大写金额

            $scope.now = new Date() //日期

            $scope.printData = value;

            $timeout(function () { //调用浏览器打印

                var showObj = $(".printArea");
                var showPrintModal = showObj.clone();
                showPrintModal.printArea();
            })

        });

    }
    //大写金额转换
    var digitUppercase = function (n) {
        var fraction = ['角', '分'];
        var digit = [
            '零', '壹', '贰', '叁', '肆',
            '伍', '陆', '柒', '捌', '玖'
        ];
        var unit = [
            ['元', '万', '亿'],
            ['', '拾', '佰', '仟']
        ];
        var head = n < 0 ? '欠' : '';
        n = Math.abs(n);
        var s = '';
        for (var i = 0; i < fraction.length; i++) {
            s += (digit[Math.floor(n * 10 * Math.pow(10, i)) % 10] + fraction[i]).replace(/零./, '');
        }
        s = s || '整';
        n = Math.floor(n);
        for (var i = 0; i < unit[0].length && n > 0; i++) {
            var p = '';
            for (var j = 0; j < unit[1].length && n > 0; j++) {
                p = digit[n % 10] + unit[1][j] + p;
                n = Math.floor(n / 10);
            }
            s = p.replace(/(零.)*零$/, '').replace(/^$/, '零') + unit[0][i] + s;
        }
        return head + s.replace(/(零.)*零元/, '元')
            .replace(/(零.)+/g, '零')
            .replace(/^整$/, '零元整');
    };
}

// 提现审核管理的面板控制器
function operationWithdrawalModalCtrl($scope, row, toaster, httpSvc, $uibModalInstance, init) {
    $scope.row = row;
    $scope.init = init;
    $scope.currentType = row.status;

    switch (row.status) {
        case 1:
            $scope.title = "提现审核管理"
            $scope.row.status = "5";
            $scope.isShowRemark = true;

            break;
        case 2:
            $scope.title = "划款"
            $scope.isShowReviewRemark = true;
            $scope.isShowTransfer = true;
            $scope.isReadOnly_ReviewRemark = true;
            $scope.row.status = "3";
            break;
        case 5:
            $scope.title = "复核处理"
            $scope.isShowRemark = true;
            $scope.isShowReviewRemark = true;
            $scope.isReadOnly_Remark = true;

            $scope.row.status = "2";
            break;
    }

    $scope.row.status += '';
    $scope.modifyflag = true;
    $scope.determineflag = false;
    if (row != undefined) {
        for (var i = 0; i < $scope.init.merchant.length; i++) {
            $scope.init.merchant[i].id;
            if (row.ref_id == $scope.init.merchant[i].id) {
                row.merchantName = $scope.init.merchant[i].name;
                break;
            }
        }
    }
    // 关闭
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    // 修改
    $scope.modify = function () {
        angular.element(document.getElementById("rate")).removeAttr("readonly");
        $scope.modifyflag = false;
        $scope.determineflag = true;
    }
    // 保存
    $scope.determine = function () {
        angular.element(document.getElementById("rate")).attr("readonly", "true");
        $scope.modifyflag = true;
        $scope.determineflag = false;
        if ($scope.row.rate == 1) {
            $scope.row.transfer_amount = $scope.row.amount;
        } else {
            $scope.row.transfer_amount = $scope.row.amount * $scope.row.rate;
        }
    }
    // 审核操作
    $scope.auditWithdrawal = function (row) {
        var value = {
            transferAmount: row.transferAmount,
            rate: row.rate,
            status: row.status,
            remark: row.remark,
            reviewRemark: row.review_remark,
            transferRemark: row.transfer_remark,
            id: row.id,
            refId: row.ref_id,
            currency: row.currency,
            amount: row.amount,
            realAmount: row.realAmount
        };
        httpSvc.getData('post', '/operation/getWithdrawalAudit', value).then(function (value) {
            if (value == true) {
                toaster.pop({
                    type: 'success',
                    title: '审核成功',
                    body: '审核成功'
                });
            } else {
                toaster.pop({
                    type: 'error',
                    title: '审核失败',
                    body: '审核失败'
                });
            }
            $uibModalInstance.dismiss();
        });
    }
}

// 交易查询
function transInfoCtrl($scope, $uibModal, $filter, toaster, NgTableParams, httpSvc, $http) {
    var defaultSearch = {idSearchType: 0};
    var searchInfo = angular.copy(defaultSearch);
    $scope.searchInfo = angular.copy(defaultSearch);
    $scope.orderTypeTxt = '平台订单号';
    var payTypesConcat = [];
    $scope.orderSwitch = function ($event, idType) {
        $scope.searchInfo.idSearchType = idType;
        $scope.orderTypeTxt = angular.element($event.target).text();
    };
    httpSvc.getData('post', '/trans/getInquireInit').then(function (value) {
        $scope.merchants = value.merchants;
        $scope.siteUrls = value.siteUrls;
        $scope.exceptionStatus = value.exceptionStatus;
        $scope.acquirerAccounts = value.acquirerAccounts;
        $scope.payModes = value.payModes;
        payTypesConcat = payTypesConcat.concat(value.credit, value.debit, value.yandex, value.qiwi, value.remittance);
        $scope.payTypes = payTypesConcat;
        $scope.bankStatus = value.bankStatus;
        $scope.shipStatus = value.shipStatus;
        $scope.financeStatus = value.financeStatus;
        $scope.init = value;
        getTransStatistics(searchInfo);
        $scope.transTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/trans/getTransInfo', {
                    pageNum: params.page(),
                    pageSize: params.count(),
                    orderBy: params.sorting(),
                    searchInfo: searchInfo
                }).then(function (value) {
                    params.total(value.total);
                    angular.element('.ibox-content').removeClass('sk-loading');
                    return value.rows;
                });
            }
        });
    });
    $scope.$watch('searchInfo.merId', function (newVal) {
        if ($scope.init !== undefined) {
            if (newVal !== undefined) {
                var urls = [];
                for (var i = 0; i < $scope.init.siteUrls.length; i++) {
                    if ($scope.init.siteUrls[i].merId === newVal) {
                        urls.push($scope.init.siteUrls[i]);
                    }
                }
                $scope.siteUrls = urls;
            } else {
                $scope.siteUrls = $scope.init.siteUrls;
            }
        }
    });
    $scope.$watch('searchInfo.payMode', function (newVal) {
        switch (newVal) {
            case 'Credit':
                $scope.payTypes = $scope.init.credit;
                break;
            case 'Debit':
                $scope.payTypes = $scope.init.debit;
                break;
            case 'Yandex':
                $scope.payTypes = $scope.init.yandex;
                break;
            case 'Qiwi':
                $scope.payTypes = $scope.init.qiwi;
                break;
            case 'Remittance':
                $scope.payTypes = $scope.init.remittance;
                break;
            default:
                $scope.payTypes = payTypesConcat;
                break;
        }
    });
    $scope.$watch('searchInfo.startDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions2.minDate = $scope.searchInfo.startDate;
            $scope.endDateDisable = false;
            if (oldEndDate !== undefined) {
                $scope.searchInfo.endDate = oldEndDate;
            }
        } else {
            $scope.endDateDisable = true;
            oldEndDate = $scope.searchInfo.endDate;
            $scope.searchInfo.endDate = undefined;
        }
    });
    $scope.$watch('searchInfo.endDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions1.maxDate = $scope.searchInfo.endDate;
        } else {
            $scope.dateOptions1.maxDate = new Date();
        }
    });
    var oldEndDate = null;
    $scope.endDateDisable = true;
    $scope.format = 'yyyy/MM/dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    $scope.searchOrder = function () {
        searchInfo = angular.copy($scope.searchInfo);
        getTransStatistics(searchInfo);
        $scope.transTable.page(1);
        $scope.transTable.reload();
    };
    $scope.resetForm = function () {
        $scope.orderTypeTxt = '平台订单号';
        $scope.searchInfo.idSearchType = 0;
        $scope.payTypes = payTypesConcat;
        $scope.searchInfo = angular.copy(defaultSearch);
        searchInfo = angular.copy(defaultSearch);
        getTransStatistics(searchInfo);
        $scope.transTable.page(1);
        $scope.transTable.reload();
    };
    $scope.showModal = function (order) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/trans/trans_modal',
            controller: 'transModalCtrl',
            size: 'lg',
            resolve: {
                orderInfo: function () {
                    return order;
                }
            }
        });
        modalInstance.result.then(function () {
        }, function () {
        });
    };
    $scope.exportOrder = function () {
        var title;
        var content;
        var exportInfo = angular.copy(searchInfo);
        var exportMaxSize = 50000;
        var objectLength = Object.keys(exportInfo).length;
        if (objectLength === 1) {
            title = '导出数据';
            content =
                '<div class="text-center">' +
                '<strong>请输入导出数据查询条件</strong>' +
                '</div>';
            exportModal(title, content).result.then(function () {
            }, function () {
            });
        } else {
            if ($scope.transTable.total() > exportMaxSize) {
                title = '导出数据';
                content =
                    '<div class="text-center">' +
                    '<strong>当前记录条数：' + $scope.transTable.total() + '，可导出最大条数：50000</strong>' +
                    '</div>';
                exportModal(title, content).result.then(function () {
                }, function () {
                });
            } else {
                title = '导出数据';
                content =
                    '<div class="text-center">' +
                    '<strong>（等需求3）</strong>' +
                    '</div>';
                exportModal(title, content).result.then(function () {
                    $http({
                        method: 'post',
                        url: '/trans/downloadOrderInfo',
                        data: exportInfo,
                        responseType: 'blob'
                    }).then(function (value) {
                        var blob = new Blob([value.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
                        var objectUrl = URL.createObjectURL(blob);
                        var a = document.createElement("a");
                        a.style = "display: none";
                        a.href = objectUrl;
                        a.download = '订单导出' + $filter('date')(Date.now(), 'yyyyMMddHHmm') + '.xlsx';
                        document.body.appendChild(a);
                        a.click();
                        window.URL.revokeObjectURL(objectUrl);
                        a.remove();
                        toaster.pop({
                            type: 'success',
                            title: '导出数据',
                            body: '导出数据成功！'
                        });
                    }, function (reason) {
                        toaster.pop({
                            type: 'error',
                            title: '导出数据',
                            body: '导出数据失败！'
                        });
                        console.log(reason);
                    });
                }, function () {
                });
            }
        }

        function exportModal(title, content) {
            return $uibModal.open({
                templateUrl: '/views/common/alert_modal',
                controller: 'alertModalCtrl',
                resolve: {
                    title: function () {
                        return title;
                    },
                    content: function () {
                        return content;
                    }
                }
            });
        }
    };

    function getTransStatistics(value) {
        httpSvc.getData('post', '/trans/getStatistics', value).then(function (value1) {
            $scope.totalCurrency = value1.totalCurrency;
            $scope.totalSuccess = value1.orderStatistics.totalSuccess;
            $scope.totalAmount = value1.orderStatistics.totalRmbAmount;
            $scope.totalSAmount = value1.orderStatistics.totalSuccessRmbAmount;
        });
    }
}

// 交易查询-交易详情弹窗
function transModalCtrl($scope, $uibModalInstance, orderInfo, httpSvc) {
    $scope.financeShow = false;
    $scope.changeShow = false;
    $scope.cargoShow = false;
    if (orderInfo.financeStatus === 1) {
        $scope.financeShow = true;
    }
    $scope.orderInfo = orderInfo;
    httpSvc.getData('post', '/trans/getDetail', orderInfo).then(function (value) {
        $scope.orderDetail = value.orderDetail;
        $scope.cardHolder = value.cardHolder;
        $scope.cargoTrack = value.cargoTrack;
        $scope.orderChange = value.orderChange;
        $scope.orderGoods = value.orderGoods;
        if ($scope.orderChange != null && $scope.orderChange !== undefined && $scope.orderChange.length > 0) {
            $scope.changeShow = true;
        }
        if ($scope.cargoTrack != null && $scope.cargoTrack !== undefined) {
            $scope.cargoShow = true;
        }
        angular.element('.ibox-content').removeClass('sk-loading');
    });
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    }
}

// 交易变更
function transChangeCtrl($scope, $uibModal, $filter, toaster, NgTableParams, httpSvc) {
    var defaultSearch = {idSearchType: 0, bankStatus: 0};
    var searchInfo = angular.copy(defaultSearch);
    $scope.searchInfo = angular.copy(defaultSearch);
    $scope.orderTypeTxt = '平台订单号';
    var totalItems;
    var merWeb = [];
    var payTypesConcat = [];
    var oneSecond = 1000;
    var oneMinute = oneSecond * 60;
    var oneHour = oneMinute * 60;
    var oneDay = oneHour * 24;
    var maxDay = 45;

    $scope.orderSwitch = function ($event, idType) {
        $scope.searchInfo.idSearchType = idType;
        $scope.orderTypeTxt = angular.element($event.target).text();
    };
    httpSvc.getData('post', '/trans/getInquireInit').then(function (value) {
        $scope.merchants = value.merchants;
        $scope.siteUrls = value.siteUrls;
        $scope.exceptionStatus = value.exceptionStatus;
        $scope.acquirerAccounts = value.acquirerAccounts;
        $scope.payModes = value.payModes;
        payTypesConcat = payTypesConcat.concat(value.credit, value.debit, value.yandex, value.qiwi, value.remittance);
        $scope.payTypes = payTypesConcat;
        $scope.bankStatus = value.bankStatus;
        $scope.shipStatus = value.shipStatus;
        $scope.financeStatus = value.financeStatus;
        $scope.init = value;
        $scope.transTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/trans/getTransInfo', {
                    pageNum: params.page(),
                    pageSize: params.count(),
                    orderBy: params.sorting(),
                    searchInfo: searchInfo
                }).then(function (value) {
                    params.total(value.total);
                    angular.element('.ibox-content').removeClass('sk-loading');
                    return value.rows;
                });
            }
        });
    });
    $scope.$watch('searchInfo.merId', function (newVal) {
        if ($scope.init !== undefined) {
            if (newVal !== undefined) {
                var urls = [];
                for (var i = 0; i < $scope.init.siteUrls.length; i++) {
                    if ($scope.init.siteUrls[i].merId === newVal) {
                        urls.push($scope.init.siteUrls[i]);
                    }
                }
                $scope.siteUrls = urls;
            } else {
                $scope.siteUrls = $scope.init.siteUrls;
            }
        }
    });
    $scope.$watch('searchInfo.startDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions2.minDate = $scope.searchInfo.startDate;
            $scope.endDateDisable = false;
            if (oldEndDate !== undefined) {
                $scope.searchInfo.endDate = oldEndDate;
            }
        } else {
            $scope.endDateDisable = true;
            oldEndDate = $scope.searchInfo.endDate;
            $scope.searchInfo.endDate = undefined;
        }
    });
    $scope.$watch('searchInfo.endDate', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions1.maxDate = $scope.searchInfo.endDate;
        } else {
            $scope.dateOptions1.maxDate = new Date();
        }
    });
    // Datepicker
    var oldEndDate = null;
    $scope.endDateDisable = true;

    $scope.format = 'yyyy/MM/dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };

    $scope.searchOrder = function () {
        searchInfo = angular.copy($scope.searchInfo);
        $scope.transTable.page(1);
        $scope.transTable.reload();
    };

    $scope.resetForm = function () {
        $scope.payTypes = payTypesConcat;
        $scope.searchInfo = angular.copy(defaultSearch);
        searchInfo = angular.copy(defaultSearch);
        $scope.transTable.page(1);
        $scope.transTable.reload();
    };

    // angular Modal
    $scope.showModal = function () {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/trans/trans_upload_modal',
            controller: 'transUploadModalCtrl',
            size: 'lg'
        });
        modalInstance.result.then(function () {
        }, function () {

        });
    };

    $scope.showChangeModal = function (order, type) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/trans/trans_change_modal',
            controller: 'transChangeModalCtrl',
            resolve: {
                orderInfo: function () {
                    return order;
                },
                type: function () {
                    return type;
                }
            }
        });
        modalInstance.result.then(function (success) {
            if (success) {
                $scope.transTable.reload();
            }
        }, function (fail) {

        });
    }
}

// 交易变更弹窗
function transChangeModalCtrl($scope, $uibModalInstance, httpSvc, toaster, orderInfo, type) {
    $scope.changeDisabled = true;
    $scope.orderInfo = orderInfo;
    $scope.orderChange = {'type': type};
    $scope.type = type;
    httpSvc.getData('post', '/trans/getMerchantOrder', orderInfo.id).then(function (value) {
        $scope.merchantOrder = value;
        $scope.orderChange['orderId'] = orderInfo.id;
        $scope.maxAmount = ($scope.merchantOrder.sourceAmount -
            ($scope.merchantOrder.sourceRefund === undefined ? 0 : $scope.merchantOrder.sourceRefund) -
            ($scope.merchantOrder.sourceProtest === undefined ? 0 : $scope.merchantOrder.sourceProtest)).toFixed(2);
        angular.element('.ibox-content').removeClass('sk-loading');
    });
    $scope.changeConfirm = function () {
        httpSvc.getData('post', '/trans/orderChange', $scope.orderChange).then(function (value) {
            if (value) {
                toaster.pop({
                    type: 'success',
                    title: '订单变更',
                    body: '订单变更成功！'
                });
                $uibModalInstance.close(value);
            } else {
                toaster.pop({
                    type: 'error',
                    title: '订单变更',
                    body: '订单变更失败！'
                });
            }
        });
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    $scope.$watch('orderChange.reasons', function (newVal) {
        if (newVal !== undefined && newVal != null && newVal.trim() !== '') {
            $scope.changeDisabled = !($scope.orderChange.amount !== undefined && $scope.orderChange.amount != null && $scope.orderChange.amount !== 0);
        } else {
            $scope.changeDisabled = true;
        }
    });
    $scope.$watch('orderChange.amount', function (newVal) {
        if (newVal !== undefined && newVal != null && newVal !== 0 && $scope.orderChange.reasons !== undefined && $scope.orderChange.reasons != null && $scope.orderChange.reasons.trim() !== '') {
            $scope.changeDisabled = !($scope.orderChange.reasons !== undefined && $scope.orderChange.reasons != null && $scope.orderChange.reasons.trim() !== '');
        } else {
            $scope.changeDisabled = true;
        }
    });
}

// 交易批量操作弹窗
function transUploadModalCtrl($scope, $uibModalInstance, httpSvc, FileUploader, toaster, csvExp, NgTableParams) {
    $scope.changeTableShow = false;
    $scope.changeList = [];
    $scope.typeSelect = [{id: '', title: ''},
        {id: '1', title: '冻结'},
        {id: '2', title: '全额退款'},
        {id: '3', title: '部分退款'},
        {id: '4', title: '全额拒付'},
        {id: '5', title: '部分拒付'}];
    $scope.uploader = new FileUploader({
        url: '/trans/batchOperation'
    });
    $scope.uploader.filters.push({
        name: 'fileFilter',
        fn: function (item) {
            if (item.type === 'application/vnd.ms-excel') {
                return myFilter(item.name);
            }
            if (item.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') {
                return myFilter(item.name);
            }

            function myFilter(name) {
                var fileName = name.split('.');
                switch (fileName[0]) {
                    case '批量冻结':
                        return true;
                    case '批量退款':
                        return true;
                    case '批量拒付':
                        return true;
                    default:
                        break;
                }
                toaster.pop({
                    type: 'error',
                    title: '订单批量处理',
                    body: '文件名不符合格式要求！'
                });
                return false;
            }
        }
    });
    $scope.uploader.onErrorItem = function (item, response, status, headers) {
        toaster.pop({
            type: 'error',
            title: '批量操作',
            body: '文件：' + item.file.name + ' 上传失败！'
        });
    };
    $scope.uploader.onCompleteItem = function (item, response, status) {
        if (status === 200) {
            toaster.pop({
                type: 'success',
                title: '批量操作',
                body: '文件：' + item.file.name + ' 上传成功！'
            });
            console.log(response);
            $scope.changeList = $scope.changeList.concat(response);
        }
    };
    $scope.uploader.onCompleteAll = function () {
        if ($scope.changeList.length > 0) {
            $scope.changeTable = new NgTableParams({}, {
                dataset: $scope.changeList
            });
            $scope.changeTableShow = true;
        }
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss('cancel');
    };
    $scope.example = function (type) {
        var csvData = {
            'data': [{'orderId': 1800000000000, 'amount': 100.00, 'reasons': '退款理由', 'remark': '非必填'}],
            'fileName': '批量退款',
            'columns': {
                'title': ['平台订单号', '退款金额', '理由', '备注'],
                'key': ['orderId', 'amount', 'reasons', 'remark']
            }
        };
        if (type === 4) {
            csvData = {
                'data': [{'orderId': 1800000000000, 'reasons': '拒付理由', 'remark': '非必填'}],
                'fileName': '批量拒付',
                'columns': {
                    'title': ['平台订单号', '理由', '备注'],
                    'key': ['orderId', 'reasons', 'remark']
                }
            };
        }
        if (csvExp.export(csvData)) {
            toaster.pop({
                type: 'success',
                title: '批量操作',
                body: '示例导出成功！'
            });
        } else {
            toaster.pop({
                type: 'warning',
                title: '批量操作',
                body: '示例导出失败！'
            });
        }
    }
}

// 保证金查询
function transBondInfoCtrl($scope, $timeout, $filter, toaster, NgTableParams, httpSvc, $http) {
    var defaultSearch = {timeSearchType: 0, idSearchType: 0, bankStatus: 0};
    var searchInfo = angular.copy(defaultSearch);
    $scope.searchInfo = angular.copy(defaultSearch);
    var init;
    var totalItems;
    $scope.orderTypeTxt = '平台订单号';
    $scope.timeTypeTxt = '交易日期';
    $scope.orderSwitch = function ($event, idType) {
        $scope.searchInfo.idSearchType = idType;
        $scope.orderTypeTxt = angular.element($event.target).text();
    };
    $scope.timeSwitch = function ($event, timeSearchType) {
        $scope.searchInfo.timeSearchType = timeSearchType;
        $scope.timeTypeTxt = angular.element($event.target).text();
    };
    var oldEndDate;
    $scope.endDateDisable = true;
    $scope.format = 'yyyy/MM/dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };

    httpSvc.getData('post', '/trans/getBondInit').then(function (value) {
        init = value;
        $scope.merchants = value.merchants;
        $scope.siteUrls = value.siteUrls;
        $scope.bondStatus = value.bondStatus;
        $scope.bondTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/trans/getBondInfo', {
                    pageNum: params.page(),
                    pageSize: params.count(),
                    orderBy: params.sorting(),
                    searchInfo: searchInfo
                }).then(function (value) {
                    params.total(value.total);
                    totalItems = value.total;
                    angular.element('.ibox-content').removeClass('sk-loading');
                    return value.rows;
                });
            }
        });
    });
    $timeout(function () {
        $scope.$watch('searchInfo.merId', function (newVal) {
            if (init !== undefined) {
                if (newVal !== undefined) {
                    var urls = [];
                    for (var i = 0; i < init.siteUrls.length; i++) {
                        if (init.siteUrls[i].merId === newVal) {
                            urls.push(init.siteUrls[i]);
                        }
                    }
                    $scope.siteUrls = urls;
                } else {
                    $scope.siteUrls = init.siteUrls;
                }
            }
        });
        $scope.$watch('searchInfo.startDate', function (newVal) {
            if (newVal !== undefined && newVal !== null) {
                $scope.dateOptions2.minDate = $scope.searchInfo.startDate;
                $scope.endDateDisable = false;
                if (oldEndDate !== undefined) {
                    $scope.searchInfo.endDate = oldEndDate;
                }
            } else {
                $scope.endDateDisable = true;
                oldEndDate = $scope.searchInfo.endDate;
                $scope.searchInfo.endDate = undefined;
            }
        });
        $scope.$watch('searchInfo.endDate', function (newVal) {
            if (newVal !== undefined && newVal !== null) {
                $scope.dateOptions1.maxDate = $scope.searchInfo.endDate;
            } else {
                $scope.dateOptions1.maxDate = new Date();
            }
        });
    });
    $scope.search = function () {
        searchInfo = angular.copy($scope.searchInfo);
        $scope.bondTable.page(1);
        $scope.bondTable.reload();
    };
    $scope.resetSearchInfo = function () {
        $scope.searchInfo = angular.copy(defaultSearch);
        searchInfo = angular.copy(defaultSearch);
        $scope.bondTable.page(1);
        $scope.bondTable.reload();
    };
    $scope.exportBond = function () {
        console.log(searchInfo);
        if (totalItems <= 50000 || angular.equals(searchInfo, defaultSearch)) {
            toaster.pop({
                type: 'success',
                title: '导出数据',
                body: '导出数据中！'
            });
            $http({
                method: 'post',
                url: '/trans/downloadBondInfo',
                data: searchInfo,
                responseType: 'blob'
            }).then(function (value) {
                toaster.pop({
                    type: 'success',
                    title: '导出数据',
                    body: '导出数据成功！'
                });
                var blob = new Blob([value.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
                var objectUrl = URL.createObjectURL(blob);
                var a = document.createElement("a");
                a.style = "display: none";
                a.href = objectUrl;
                a.download = '保证金导出' + $filter('date')(Date.now(), 'yyyyMMddHHmm') + '.xlsx';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(objectUrl);
                a.remove();
            }, function (reason) {
                toaster.pop({
                    type: 'error',
                    title: '导出数据',
                    body: '导出数据失败！'
                });
                console.log(reason);
            });
        } else {
            toaster.pop({
                type: 'warning',
                title: '导出数据',
                body: '导出数据超过50 000条！'
            });
        }
    };
}

// 用户管理
function userMgmtCtrl($scope, $uibModal, toaster, NgTableParams, httpSvc) {
    $scope.delDisabled = true;
    $scope.selected = {};
    $scope.statusChange = function (row) {
        httpSvc.getData('post', '/admin/user/update', {
            id: row.id,
            userName: row.userName,
            available: !row.available
        }).then(function (value) {
            if (value) {
                toaster.pop({
                    type: 'success',
                    title: '用户管理',
                    body: '更新用户状态成功！'
                });
                tableReload();
            } else {
                toaster.pop({
                    type: 'error',
                    title: '用户管理',
                    body: '更新用户状态失败！'
                });
            }
        });
    };

    httpSvc.getData('post', '/admin/role/getAll').then(function (value) {
        $scope.allRole = value;
        httpSvc.getData('post', '/admin/user/getAll').then(function (value1) {
            $scope.userTable = new NgTableParams({}, {
                dataset: value1
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    });

    $scope.showModal = function () {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/user/user_register_modal',
            controller: 'userRegisterModalCtrl',
            resolve: {
                allRole: function () {
                    return $scope.allRole;
                }
            }
        });
        modalInstance.result.then(function () {
            tableReload();
        }, function () {
            // tableReload();
        });
    };

    $scope.edit = function (user, type) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/user/user_change_modal',
            controller: 'userChangeModalCtrl',
            resolve: {
                userInfo: function () {
                    return user;
                },
                type: function () {
                    return type;
                },
                allRole: function () {
                    return $scope.allRole;
                }
            }
        });
        modalInstance.result.then(function () {
            tableReload();
        }, function () {
        });
    };

    $scope.search = function (searchInfo) {
        angular.extend($scope.userTable.filter(), searchInfo);
    };

    $scope.reset = function () {
        $scope.searchInfo = {};
        $scope.userTable.filter({});
    };

    $scope.del = function () {
        var idList = [];
        for (var id in $scope.selected) {
            if ($scope.selected[id]) {
                idList.push(id);
            }
        }
        httpSvc.getData('post', '/admin/user/delete', idList).then(function (value) {
            if (value) {
                $scope.selected = {};
                toaster.pop({
                    type: 'success',
                    title: '用户管理',
                    body: '删除用户成功！'
                });
                tableReload();
            } else {
                toaster.pop({
                    type: 'error',
                    title: '用户管理',
                    body: '删除用户失败！'
                });
            }
        });
    };

    $scope.delDisabled = function () {
        for (var id in $scope.selected) {
            if ($scope.selected[id]) {
                return false;
            }
        }
        return true;
    };

    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/admin/user/getAll').then(function (value) {
            for (var i = 0; i < value.length; i++) {
                for (var j = 0; j < $scope.allRole.length; j++) {
                    if (value[i].roleId === $scope.allRole[j].id) {
                        value[i]['role'] = $scope.allRole[j];
                        break;
                    }
                }
            }
            $scope.userTable.settings({
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
}

// 用户注册弹窗
function userRegisterModalCtrl($scope, $uibModalInstance, httpSvc, toaster, allRole) {
    // $scope.nextDisable = true;
    $scope.nameValid = false;
    $scope.passwordValid = false;
    $scope.allRole = allRole;

    $scope.userNameBlur = function ($event, userName) {
        if (!verification(userName, $event.target)) {
            httpSvc.getData('post', '/admin/user/isExist', JSON.stringify(userName)).then(function (value) {
                if (value) {
                    $scope.nameValid = false;
                    verification(undefined, $event.target);
                } else {
                    $scope.nameValid = true;
                    verification(value, $event.target);
                }
            });
        } else {
            $scope.nameValid = false;
        }
    };

    $scope.passwordKeyUp = function ($event, password) {
        if (password === undefined || password.length < 6) {
            angular.element($event.target).parent().removeClass('has-success');
            angular.element($event.target).parent().addClass('has-error');
        } else {
            angular.element($event.target).parent().removeClass('has-error');
            angular.element($event.target).parent().addClass('has-success');
        }
    };

    $scope.passwordBKeyUp = function ($event, passwordB, password) {
        if (passwordB !== password) {
            $scope.passwordValid = false;
            angular.element($event.target).parent().removeClass('has-success');
            angular.element($event.target).parent().addClass('has-error');
        } else {
            $scope.passwordValid = true;
            angular.element($event.target).parent().removeClass('has-error');
            angular.element($event.target).parent().addClass('has-success');
        }
    };

    $scope.namesBlur = $scope.phoneBlur = $scope.emailBlur = $scope.passwordBlur = $scope.passwordBBlur = function ($event, value) {
        verification(value, $event.target)
    };

    $scope.myRegex = function ($event, value) {
        myRegex($event, value, 'g');
    };

    $scope.nextBtn = function (tab) {
        if (tab !== 3) {
            $scope.tab += 1;
        } else {
            if ($scope.register.roleId === undefined) {
                $scope.register.roleId = 0;
            }
            httpSvc.getData('post', '/admin/user/register', $scope.register).then(function (value) {
                if (value.id !== undefined) {
                    $scope.register = null;
                    toaster.pop({
                        type: 'success',
                        title: '用户管理',
                        body: '用户注册成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '用户管理',
                        body: '用户注册失败！'
                    });
                }
            });
        }
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };

    $scope.nextDisable = function (myForm, tab) {
        switch (tab) {
            case 1:
                return !(myForm.userName.$valid && myForm.password.$valid && myForm.passwordB.$valid && $scope.nameValid && $scope.passwordValid);
            case 2:
                return !(myForm.realName.$valid && myForm.mobile.$valid && myForm.email.$valid);
            default:
                return false;
        }
    }
}

// 用户变更弹窗
function userChangeModalCtrl($scope, $uibModalInstance, httpSvc, toaster, userInfo, type, allRole) {
    $scope.tab = type;
    $scope.passwordValid = false;
    $scope.changType = type;
    $scope.changeInfo = angular.copy(userInfo);
    $scope.changeInfo.roleId += '';

    if (type === 1) {
        $scope.allRole = allRole;
    }

    $scope.passwordKeyUp = function ($event, password) {
        if (password === undefined || password.length < 6) {
            angular.element($event.target).parent().removeClass('has-success');
            angular.element($event.target).parent().addClass('has-error');
        } else {
            angular.element($event.target).parent().removeClass('has-error');
            angular.element($event.target).parent().addClass('has-success');
        }
    };

    $scope.passwordBKeyUp = function ($event, passwordB, password) {
        if (passwordB !== password) {
            $scope.passwordValid = false;
            angular.element($event.target).parent().removeClass('has-success');
            angular.element($event.target).parent().addClass('has-error');
        } else {
            $scope.passwordValid = true;
            angular.element($event.target).parent().removeClass('has-error');
            angular.element($event.target).parent().addClass('has-success');
        }
    };

    $scope.namesBlur = $scope.phoneBlur = $scope.emailBlur = function ($event, value) {
        verification(value, $event.target);
    };

    $scope.changeUser = function () {
        if ($scope.changeInfo === undefined || $scope.changeInfo === null) {
            $scope.changeInfo = {};
            $scope.changeInfo.roleId = '0';
        }
        $scope.changeInfo.id = userInfo.id;
        httpSvc.getData('post', '/admin/user/update', $scope.changeInfo).then(function (value) {
            if (value) {
                toaster.pop({
                    type: 'success',
                    title: '用户变更',
                    body: type === 1 ? '信息编辑成功！' : '密码变更成功！'
                });
                $uibModalInstance.close();
            } else {
                toaster.pop({
                    type: 'error',
                    title: '用户变更',
                    body: type === 1 ? '信息编辑失败！' : '密码变更失败！'
                });
            }
        });
    };

    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };

    $scope.nextDisable = function (myForm, tab) {
        switch (tab) {
            case 1:
                return !(myForm.realName.$valid && myForm.mobile.$valid && myForm.email.$valid && !angular.equals($scope.changeInfo, userInfo));
            case 2:
                return !(myForm.password.$valid && myForm.passwordB.$valid && $scope.passwordValid);
            default:
                return false;
        }
    }
}

// 角色管理
function roleMgmtCtrl($scope, $uibModal, toaster, httpSvc, NgTableParams) {
    $scope.statusChange = function (row) {
        httpSvc.getData('post', '/admin/role/update', {id: row.id, available: !row.available}).then(function (value) {
            if (value) {
                toaster.pop({
                    type: 'success',
                    title: '角色管理',
                    body: '更新角色状态成功！'
                });
                tableReload();
            } else {
                toaster.pop({
                    type: 'error',
                    title: '角色管理',
                    body: '更新角色状态失败！'
                });
            }
        });
    };
    httpSvc.getData('post', '/admin/role/getAllPrivileges').then(function (value) {
        $scope.menus = value;
        httpSvc.getData('post', '/admin/role/getAll').then(function (value1) {
            $scope.roleTable = new NgTableParams({}, {
                dataset: value1
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    });

    $scope.showModal = $scope.edit = function (type, roleInfo) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/user/role_modal',
            controller: 'roleModalCtrl',
            resolve: {
                type: function () {
                    return type;
                },
                roleInfo: function () {
                    return roleInfo;
                },
                menus: function () {
                    return $scope.menus;
                }
            }
        });
        modalInstance.result.then(function () {
            tableReload()
        }, function () {
        });
    };

    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/admin/role/getAll').then(function (value) {
            $scope.roleTable.settings({
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
}

// 新增角色弹窗
function roleModalCtrl($scope, $uibModalInstance, httpSvc, toaster, type, roleInfo, menus) {
    $scope.oneAtATime = false;
    if (type === 0) {
        $scope.nameValid = false;
        $scope.roleInfo = {privilegesList: []};
    } else {
        $scope.nameValid = true;
        $scope.roleInfo = angular.copy(roleInfo);
        if ($scope.roleInfo.privilegesId !== undefined) {
            $scope.roleInfo.privilegesList = $scope.roleInfo.privilegesId.replace(/[^,\d]/g, '').split(',');
        } else {
            $scope.roleInfo.privilegesList = [];
        }
    }

    $scope.exists = function (value, selected) {
        if (value === undefined || selected === undefined) {
            return false;
        }
        return selected.indexOf(value) > -1;
    };
    $scope.toggle = function (value, selected) {
        var index = selected.indexOf(value);
        if (index > -1) {
            selected.splice(index, 1);
        } else {
            selected.push(value);
        }
    };
    $scope.menu = [];
    for (var i = 0; i < menus.length; i++) {
        if (menus[i].parentId === undefined) {
            var menu = menus[i];
            menu['submenu'] = [];
            for (var j = 0; j < menus.length; j++) {
                if (menus[j].parentId === menus[i].id) {
                    menu.submenu.push(menus[j]);
                }
            }
            $scope.menu.push(menu);
        }
    }
    $scope.nameBlur = function ($event, roleName) {
        if (!verification(roleName, $event.target)) {
            httpSvc.getData('post', '/admin/role/isExist', JSON.stringify(roleName)).then(function (value) {
                if (value) {
                    verification(undefined, $event.target);
                    $scope.nameValid = false;
                } else {
                    verification(value, $event.target);
                    $scope.nameValid = true;
                }
            });
        }
    };
    $scope.nextDisabled = function (myForm) {
        if (type === 1) {
            return !(myForm.roleName.$valid && $scope.nameValid && !angular.equals($scope.roleInfo, roleInfo));
        } else {
            return !(myForm.roleName.$valid && $scope.nameValid);
        }
    };
    $scope.confirmBtn = function () {
        $scope.roleInfo.privilegesId = $scope.roleInfo.privilegesList.toString();
        if (type === 0) {
            httpSvc.getData('post', '/admin/role/add', $scope.roleInfo).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '角色管理',
                        body: '新增角色成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '角色管理',
                        body: '新增角色失败！'
                    });
                }
            });
        } else {
            httpSvc.getData('post', '/admin/role/update', $scope.roleInfo).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '角色管理',
                        body: '更新角色成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '角色管理',
                        body: '更新角色失败！'
                    });
                }
            });
        }
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
}

// 拒付统计
function refusedStatisticsCtrl($scope, $timeout, $filter, NgTableParams, httpSvc) {
    var init;
    $scope.showEndDateRmbCount = false;
    httpSvc.getData('post', '/trans/getRefusedInquireInit').then(function (value) {
        $scope.merchants = value.merchants;
        $scope.siteUrls = value.siteUrls;
        $scope.country = value.country;
        init = value;
        httpSvc.getData('post', '/trans/getRefusedStatistics', searchInfo).then(function (value1) {
            for (var i = 0; i < value1.length; i++) {
                value1[i].count *= 1;
                value1[i].refusedCount *= 1;
                value1[i]['refusePercent'] = $filter('number')(value1[i].refusedCount / value1[i].count * 100, 2) * 1;
            }
            $scope.refusedTable = new NgTableParams({
                sorting: {refusePercent: 'desc'}
            }, {
                dataset: value1
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    });
    var searchInfo = {};
    $scope.format = 'yyyy/MM/dd';
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions3 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions4 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.popup1 = {
        opend: false
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.popup3 = {
        opend: false
    };
    $scope.popup4 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    $scope.openDatepicker3 = function () {
        $scope.popup3.opend = !$scope.popup3.opend;
    };
    $scope.openDatepicker4 = function () {
        $scope.popup4.opend = !$scope.popup4.opend;
    };

    $timeout(function () {
        $scope.$watch('searchInfo.merId', function (newVal) {
            if (init !== undefined) {
                if (newVal !== undefined) {
                    var urls = [];
                    for (var i = 0; i < init.siteUrls.length; i++) {
                        if (init.siteUrls[i].merId === newVal) {
                            urls.push(init.siteUrls[i]);
                        }
                    }
                    $scope.siteUrls = urls;
                } else {
                    $scope.siteUrls = init.siteUrls;
                }
            }
        });
        $scope.$watch('startDate', function (newVal) {
            if (newVal !== undefined) {
                $scope.dateOptions2.minDate = $scope.startDate;
            } else {
                $scope.dateOptions2.minDate = null;
            }
        });
        $scope.$watch('endDate', function (newVal) {
            if (newVal !== undefined) {
                $scope.dateOptions1.maxDate = $scope.endDate;
            } else {
                $scope.dateOptions1.maxDate = new Date();
            }
        });
        $scope.$watch('refusedStartDate', function (newVal) {
            if (newVal !== undefined) {
                $scope.dateOptions4.minDate = $scope.refusedStartDate;
            } else {
                $scope.dateOptions4.minDate = null;
            }
        });
        $scope.$watch('refusedEndDate', function (newVal) {
            if (newVal !== undefined) {
                $scope.dateOptions3.maxDate = $scope.refusedEndDate;
            } else {
                $scope.dateOptions3.maxDate = new Date();
            }
        });
    });

    $scope.search = function (searchInfo) {
        tableReload(searchInfo);
    };

    $scope.resetForm = function () {
        $scope.searchInfo = {};
        tableReload({});
    };

    function tableReload(searchInfo) {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/trans/getRefusedStatistics', searchInfo === undefined ? {} : searchInfo).then(function (value) {
            for (var i = 0; i < value.length; i++) {
                for (var j = 0; j < $scope.merchants.length; j++) {
                    if (value[i].merId === $scope.merchants[j].id) {
                        value[i]['merName'] = $scope.merchants[j].name;
                        break;
                    }
                }
                value[i]['refusePercent'] = $filter('number')(value[i].refusedCount / value[i].count * 100, 2);
                if (value[i].refusedEndDateRmbCount === undefined) {
                    value[i].refusedEndDateRmbCount = 0;
                }
            }
            if (searchInfo === undefined || searchInfo.refusedStartDate === undefined && searchInfo.refusedEndDate !== undefined) {
                $scope.refusedTable.sorting({refusedEndDateRmbCount: 'desc'});
                $scope.showEndDateRmbCount = true;
            } else {
                $scope.showEndDateRmbCount = false;
            }
            $scope.refusedTable.settings({
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
}

// 银行管理
function acquirerBankCtrl($scope, $uibModal, NgTableParams, httpSvc, toaster) {
    var bank;
    $scope.selected = {};
    httpSvc.getData('post', '/system/getConstantByGroupNameAndSortValueIsNotNULL', JSON.stringify('Status')).then(function (value) {
        $scope.bankStatus = value;
        httpSvc.getData('post', '/acquirer/bank/getAll').then(function (value) {
            bank = value;
            $scope.bankTable = new NgTableParams({}, {
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    });
    $scope.statusChange = function ($event, row) {
        httpSvc.getData('post', '/acquirer/bank/update', {id: row.id, status: row.status ? 0 : 1}).then(function (value) {
            if (value) {
                toaster.pop({
                    type: 'success',
                    title: '收单银行',
                    body: '更新银行状态成功！'
                });
                angular.element($event.target).toggleClass('active');
                angular.element($event.target).toggleClass('btn-primary');
                angular.element($event.target).toggleClass('btn-disabled');
                angular.element($event.target).hasClass('active') ?
                    angular.element($event.target).text('启用') :
                    angular.element($event.target).text('禁用');
            } else {
                toaster.pop({
                    type: 'error',
                    title: '收单银行',
                    body: '更新银行状态失败！'
                });
            }
        });
    };
    $scope.showModal = $scope.edit = function (type, bankInfo) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/bank_area/acquirer_bank_modal',
            controller: 'acquirerBankModalCtrl',
            resolve: {
                type: function () {
                    return type;
                },
                bankInfo: function () {
                    return bankInfo;
                }
            }
        });
        modalInstance.result.then(function () {
            tableReload()
        }, function () {
        });
    };
    $scope.search = function (searchInfo) {
        angular.extend($scope.bankTable.filter(), searchInfo);
    };
    $scope.reset = function () {
        $scope.searchInfo = {};
        $scope.bankTable.filter({});
    };
    $scope.del = function () {
        var idList = [];
        for (var id in $scope.selected) {
            if ($scope.selected[id]) {
                idList.push(id);
            }
        }
        var title = '删除确认';
        var content =
            '<div class="text-center">' +
            '<strong>确定删除这' + idList.length + '条数据吗？</strong>' +
            '</div>';
        var modalInstance = $uibModal.open({
            templateUrl: '/views/common/alert_modal',
            controller: 'alertModalCtrl',
            resolve: {
                title: function () {
                    return title;
                },
                content: function () {
                    return content;
                }
            }
        });
        modalInstance.result.then(function () {
            httpSvc.getData('post', '/acquirer/bank/delete', idList).then(function (value) {
                if (value.length === 0) {
                    toaster.pop({
                        type: 'success',
                        title: '收单银行',
                        body: '删除收单银行成功！'
                    });
                    tableReload();
                } else {
                    var toasterBody = '';
                    for (var i = 0; i < value.length; i++) {
                        for (var j = 0; j < bank.length; j++) {
                            if (value[i] === bank[j].id) {
                                toasterBody += bank[j].name;
                                toasterBody += '；';
                                break;
                            }
                        }
                    }
                    toaster.pop({
                        type: 'warning',
                        title: '收单银行',
                        body: '存在收单机构的银行为' + toasterBody + '无法删除！',
                        timeout: 0
                    });
                }
                $scope.selected = {};
            });
        }, function () {
        });
    };
    $scope.delDisabled = function () {
        for (var id in $scope.selected) {
            if ($scope.selected[id]) {
                return false;
            }
        }
        return true;
    };

    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/acquirer/bank/getAll').then(function (value) {
            $scope.bankTable.settings({
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
}

// 银行弹窗
function acquirerBankModalCtrl($scope, $uibModalInstance, httpSvc, toaster, type, bankInfo) {
    $scope.type = type;
    if (type === 1) {
        $scope.bankInfo = angular.copy(bankInfo);
    }
    httpSvc.getData('post', '/system/getConstantByGroupName', JSON.stringify('Status')).then(function (value) {
        $scope.bankStatus = value;
    });
    $scope.nameBlur = $scope.statusBlur = function ($event, bankName) {
        verification(bankName, $event.target);
    };
    $scope.$watch('bankInfo.status', function (newVal) {
        if (newVal !== undefined) {
            angular.element('#bank-status').parent().removeClass('has-error');
            angular.element('#bank-status').parent().addClass('has-success');
        }
    });
    $scope.nextBtn = function () {
        if (type === 0) {
            httpSvc.getData('post', '/acquirer/bank/add', $scope.bankInfo).then(function (value) {
                if (value) {
                    $scope.bankInfo = null;
                    toaster.pop({
                        type: 'success',
                        title: '银行管理',
                        body: '银行添加成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '银行管理',
                        body: '银行添加失败！'
                    });
                }
            });
        } else {
            httpSvc.getData('post', '/acquirer/bank/update', $scope.bankInfo).then(function (value) {
                if (value) {
                    $scope.bankInfo = null;
                    toaster.pop({
                        type: 'success',
                        title: '银行管理',
                        body: '银行修改成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '银行管理',
                        body: '银行修改失败！'
                    });
                }
            });
        }
    };
    $scope.nextDisabled = function (myForm) {
        return !(myForm.name.$valid && myForm.bkStatus.$valid && !angular.equals($scope.bankInfo, bankInfo));
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
}

// 收单机构管理
function acquirerCtrl($scope, $uibModal, NgTableParams, httpSvc, toaster) {
    var acquirer;
    var init;
    $scope.selected = {};
    httpSvc.getData('post', '/acquirer/getAcquirerInit').then(function (value) {
        init = value;
        $scope.payMode = value.payMode;
        $scope.currency = value.currency;
        $scope.bank = value.bank;
        $scope.acquirerStatus = value.status;
        $scope.continent = value.continent;
        $scope.acquirerType = value.acquirerType;
        httpSvc.getData('post', '/acquirer/getAllAcquirer').then(function (value1) {
            var currency;
            var risk;
            var i, j, k;
            for (i = 0; i < value1.length; i++) {
                currency = value1[i].currency.replace(/[^a-zA-z,]/g, '').split(',');
                value1[i]['currencyCN'] = '';
                value1[i]['riskCN'] = '';
                for (j = 0; j < currency.length; j++) {
                    for (k = 0; k < value.currency.length; k++) {
                        if (currency[j].trim() === value.currency[k].firstValue) {
                            value1[i]['currencyCN'] += value.currency[k].name + '，';
                            break;
                        }
                    }
                }
                risk = value1[i].risk.replace(/[^a-zA-z,]/g, '').split(',');
                for (j = 0; j < risk.length; j++) {
                    for (k = 0; k < value.risk.length; k++) {
                        if (risk[j].trim() === value.risk[k].firstValue) {
                            value1[i]['riskCN'] += value.risk[k].name + '，';
                            break;
                        }
                    }
                }
            }
            acquirer = value1;
            $scope.acquirerTable = new NgTableParams({}, {
                dataset: value1
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    });
    $scope.statusChange = function ($event, row) {
        httpSvc.getData('post', '/acquirer/updateAcquirer', {id: row.id, status: row.status ? 0 : 1}).then(function (value) {
            if (value) {
                toaster.pop({
                    type: 'success',
                    title: '收单机构',
                    body: '更新收单机构状态成功！'
                });
                tableReload();
            } else {
                toaster.pop({
                    type: 'error',
                    title: '收单机构',
                    body: '更新收单机构状态失败！'
                });
            }
        });
    };
    $scope.showModal = $scope.edit = function (type, acquirerInfo) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/bank_area/acquirer_modal',
            controller: 'acquirerModalCtrl',
            resolve: {
                type: function () {
                    return type;
                },
                acquirerInfo: function () {
                    return acquirerInfo;
                },
                init: function () {
                    return init;
                }
            }
        });
        modalInstance.result.then(function () {
            tableReload()
        }, function () {
        });
    };
    $scope.search = function (searchInfo) {
        angular.extend($scope.acquirerTable.filter(), searchInfo);
    };
    $scope.reset = function () {
        $scope.searchInfo = {};
        $scope.acquirerTable.filter({});
    };
    $scope.del = function () {
        var idList = [];
        for (var id in $scope.selected) {
            if ($scope.selected[id]) {
                idList.push(id);
            }
        }
        var title = '删除确认';
        var content =
            '<div class="text-center">' +
            '<strong>确定删除这' + idList.length + '条数据吗？</strong>' +
            '</div>';
        var modalInstance = $uibModal.open({
            templateUrl: '/views/common/alert_modal',
            controller: 'alertModalCtrl',
            resolve: {
                title: function () {
                    return title;
                },
                content: function () {
                    return content;
                }
            }
        });
        modalInstance.result.then(function () {
            httpSvc.getData('post', '/acquirer/deleteAcquirer', idList).then(function (value) {
                if (value.length === 0) {
                    toaster.pop({
                        type: 'success',
                        title: '收单机构',
                        body: '删除收单账户成功！'
                    });
                    tableReload();
                } else {
                    var toasterBody = '';
                    for (var i = 0; i < value.length; i++) {
                        for (var j = 0; j < acquirer.length; j++) {
                            if (value[i] === acquirer[j].id) {
                                toasterBody += acquirer[j].name;
                                toasterBody += '；';
                                break;
                            }
                        }
                    }
                    toaster.pop({
                        type: 'warning',
                        title: '收单机构',
                        body: '存在收单账户的收单机构为' + toasterBody + '无法删除！',
                        timeout: 0
                    });
                }
                $scope.selected = {};
            });
        }, function () {
        });
    };
    $scope.delDisabled = function () {
        for (var id in $scope.selected) {
            if ($scope.selected[id]) {
                return false;
            }
        }
        return true;
    };

    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/acquirer/getAllAcquirer').then(function (value) {
            var currency;
            var risk;
            var i, j, k;
            for (i = 0; i < value.length; i++) {
                currency = value[i].currency.replace(/[^a-zA-z,]/g, '').split(',');
                value[i]['currencyCN'] = '';
                value[i]['riskCN'] = '';
                for (j = 0; j < currency.length; j++) {
                    for (k = 0; k < init.currency.length; k++) {
                        if (currency[j].trim() === init.currency[k].firstValue) {
                            value[i]['currencyCN'] += init.currency[k].name + '，';
                            break;
                        }
                    }
                }
                risk = value[i].risk.replace(/[^a-zA-z,]/g, '').split(',');
                for (j = 0; j < risk.length; j++) {
                    for (k = 0; k < init.risk.length; k++) {
                        if (risk[j].trim() === init.risk[k].firstValue) {
                            value[i]['riskCN'] += init.risk[k].name + '，';
                            break;
                        }
                    }
                }
            }
            $scope.acquirerTable.settings({
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
}

// 收单机构弹窗
function acquirerModalCtrl($scope, $uibModalInstance, $timeout, httpSvc, toaster, type, acquirerInfo, init) {
    $scope.type = type;
    $scope.acquirerType = init.acquirerType;
    $scope.acquirerStatus = init.status;
    $scope.bank = init.bank;
    $scope.currency = init.currency;
    $scope.risk = init.risk;
    $scope.payPage = init.payPage;
    $scope.continent = init.continent;
    $scope.payMode = init.payMode;
    $scope.acquirerRate = {payType: [], payTypeOld: []};
    var rateList = [];
    // type：0：新增，1、修改
    if (type === 1) {
        $scope.acquirerInfo = angular.copy(acquirerInfo);
        $scope.acquirerInfo.currency = acquirerInfo.currency.replace(/[^a-zA-z,]/g, '').split(',');
        $scope.acquirerInfo.risk = acquirerInfo.risk.replace(/[^a-zA-z,]/g, '').split(',');
        $scope.acquirerInfo.type += '';
        $scope.acquirerInfo.bankId += '';
        httpSvc.getData('post', '/acquirer/getAcquirerRateByAcquirerId', JSON.stringify(acquirerInfo.id)).then(function (value) {
            for (var i = 0; i < value.length; i++) {
                var payType = value[i].payType.split('_');
                for (var j = 0; j < init[payType[0]].length; j++) {
                    if (init[payType[0]][j].firstValue === payType[1]) {
                        init[payType[0]][j]['rate'] = value[i].rate;
                        break;
                    }
                }
                if (value[i].status === 1) {
                    $scope.acquirerRate.payType.push(payType[1]);
                }
                $scope.acquirerRate.payTypeOld.push(payType[1]);
                value[i].status = 0;
            }
            $scope.acquirerRate['rates'] = value;
        });
    } else {
        $scope.acquirerInfo = {currency: [], risk: []};
    }

    $scope.exists = function (value, selected) {
        if (value === undefined || selected === undefined) {
            return false;
        }
        return selected.indexOf(value) > -1;
    };
    $scope.toggle = function (value, selected) {
        var index = selected.indexOf(value);
        if (index > -1) {
            selected.splice(index, 1);
        } else {
            selected.push(value);
        }
    };
    $scope.someSelected = function (object) {
        return Object.keys(object).some(function (key) {
            return object[key];
        });
    };
    $scope.nameBlur = $scope.typeBlur = $scope.statusBlur = $scope.bankIdBlur = $scope.urlBlur =
        $scope.payPageBlur = $scope.scopeBlur = function ($event, name) {
            verification(name, $event.target);
        };
    $scope.$watch('acquirerInfo.payMode', function (newVal) {
        switch (newVal) {
            case 'Credit':
                $scope.payType = init.Credit;
                break;
            case 'Debit':
                $scope.payType = init.Debit;
                break;
            case 'Yandex':
                $scope.payType = init.Yandex;
                break;
            case 'Qiwi':
                $scope.payType = init.Qiwi;
                break;
            case 'Remittance':
                $scope.payType = init.Remittance;
                break;
            default:
                break;
        }
    });
    $scope.confirm = function (acquirer, activeForm) {
        switch (activeForm) {
            case 0:
                $scope.activeForm++;
                break;
            case 1:
                $scope.activeForm++;
                break;
            case 2:
                var payType;
                var i, j, k, rate, rateJson;
                acquirer.currency = acquirer.currency.toString();
                acquirer.risk = acquirer.risk.toString();
                if (type === 0) {
                    // 获取当前选择的支付方式的支付类型
                    payType = init[acquirer.payMode];
                    for (i = 0; i < payType.length; i++) {
                        // 获取当前循环的支付类型对应扣率对象的数组下标
                        var index = $scope.acquirerRate.payType.indexOf(payType[i].firstValue);
                        // 判断当前支付类型是否存在扣率
                        if (index > -1) {
                            // 循环获取对应扣率值
                            for (j = 0; j < $scope.payType.length; j++) {
                                if ($scope.acquirerRate.payType[index] === $scope.payType[j].firstValue) {
                                    rate = $scope.payType[j].rate;
                                    break;
                                }
                            }
                            // 向扣率数组插入扣率对象
                            rateJson = {
                                payType: acquirer.payMode + '_' + $scope.acquirerRate.payType[index],
                                rate: rate,
                                status: 1
                            };
                            rateList.push(rateJson);
                        }
                    }
                    acquirer['acquirerRates'] = rateList;
                    httpSvc.getData('post', '/acquirer/addAcquirer', acquirer).then(function (value) {
                        if (value) {
                            toaster.pop({
                                type: 'success',
                                title: '收单机构',
                                body: '添加收单机构成功！'
                            });
                            $uibModalInstance.close();
                        } else {
                            toaster.pop({
                                type: 'error',
                                title: '收单机构',
                                body: '添加收单机构失败！'
                            });
                        }
                    });
                } else {
                    // 循环查找已选择支付类型
                    for (i = 0; i < $scope.acquirerRate.payType.length; i++) {
                        // 判断是否已存在该支付类型
                        if ($scope.acquirerRate.payTypeOld.indexOf($scope.acquirerRate.payType[i]) > -1) {
                            // 循环查找已存在支付类型
                            for (j = 0; j < $scope.acquirerRate.rates.length; j++) {
                                payType = $scope.acquirerRate.rates[j].payType.split('_');
                                if (payType[1] === $scope.acquirerRate.payType[i]) {
                                    // 循环查找最新汇率
                                    for (k = 0; k < $scope.payType.length; k++) {
                                        // 找出对应汇率并更新对象
                                        if ($scope.payType[k].firstValue === $scope.acquirerRate.payType[i]) {
                                            $scope.acquirerRate.rates[j].rate = $scope.payType[k].rate;
                                            // 设置为启用
                                            $scope.acquirerRate.rates[j].status = 1;
                                            break;
                                        }
                                    }
                                    break;
                                }
                            }
                        } else {
                            for (j = 0; j < $scope.payType.length; j++) {
                                if ($scope.acquirerRate.payType[i] === $scope.payType[j].firstValue) {
                                    rate = $scope.payType[j].rate;
                                    break;
                                }
                            }
                            // 向扣率数组插入扣率对象
                            rateJson = {
                                payType: acquirer.payMode + '_' + $scope.acquirerRate.payType[i],
                                rate: rate,
                                status: 1
                            };
                            $scope.acquirerRate.rates.push(rateJson);
                        }
                    }

                    acquirer['acquirerRates'] = $scope.acquirerRate.rates;
                    httpSvc.getData('post', '/acquirer/updateAcquirer', acquirer).then(function (value) {
                        if (value) {
                            toaster.pop({
                                type: 'success',
                                title: '收单机构',
                                body: '修改收单机构成功！'
                            });
                            $uibModalInstance.close();
                        } else {
                            toaster.pop({
                                type: 'error',
                                title: '收单机构',
                                body: '修改收单机构失败！'
                            });
                        }
                    });
                }
                break;
        }
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    $timeout(function () {
        $scope.nextDisabled = function (myForm, activeForm) {
            switch (activeForm) {
                case 0:
                    return myForm.name.$error.required || myForm.type.$error.required ||
                        myForm.status.$error.required || myForm.bankId.$error.required ||
                        myForm.url.$error.required;
                case 1:
                    return myForm.currency.$error.required;
                case 2:
                    if ($scope.acquirerRate.payType.length !== 0) {
                        var i, j;
                        for (i = 0; i < $scope.acquirerRate.payType.length; i++) {
                            for (j = 0; j < $scope.payType.length; j++) {
                                if ($scope.acquirerRate.payType[i] === $scope.payType[j].firstValue) {
                                    return $scope.payType[j].rate === undefined || $scope.payType[j].rate === null;
                                }
                            }
                        }
                        return myForm.$error.required;
                    }
                    return true;
            }
        };
    });
}

// 收单账户管理
function acquirerAccountCtrl($scope, $uibModal, NgTableParams, httpSvc, toaster) {
    var init;
    var acquirerAccounts;
    $scope.selected = {};
    httpSvc.getData('post', '/acquirer/account/getInit').then(function (value) {
        init = value;
        $scope.acquirer = value.acquirer;
        $scope.currency = value.currency;
        $scope.accountStatus = value.status;
        httpSvc.getData('post', '/acquirer/account/getAll').then(function (value1) {
            var i, j, k, currency;
            for (i = 0; i < value1.length; i++) {
                value1[i]['currencyCN'] = '';
                currency = value1[i].currency.replace(/[^a-zA-z,]/g, '').split(',');
                for (j = 0; j < currency.length; j++) {
                    for (k = 0; k < value.currency.length; k++) {
                        if (value.currency[k].firstValue === currency[j]) {
                            value1[i]['currencyCN'] += value.currency[k].name + '，';
                            break;
                        }
                    }
                }
            }
            acquirerAccounts = value1;
            $scope.acquirerAccountTable = new NgTableParams({}, {
                dataset: value1
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    });
    $scope.statusChange = function ($event, row) {
        httpSvc.getData('post', '/acquirer/account/update', {id: row.id, status: row.status ? 0 : 1}).then(function (value) {
            if (value) {
                toaster.pop({
                    type: 'success',
                    title: '收单账户',
                    body: '更新收单账户状态成功！'
                });
                tableReload();
            } else {
                toaster.pop({
                    type: 'error',
                    title: '收单账户',
                    body: '更新收单账户状态失败！'
                });
            }
        });
    };
    $scope.search = function (searchInfo) {
        angular.extend($scope.acquirerAccountTable.filter(), searchInfo);
    };
    $scope.reset = function () {
        $scope.searchInfo = {};
        $scope.acquirerAccountTable.filter({});
    };
    $scope.showModal = $scope.edit = function (type, acquirerAccountInfo) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/bank_area/acquirer_account_modal',
            controller: 'acquirerAccountModalCtrl',
            resolve: {
                type: function () {
                    return type;
                },
                acquirerAccountInfo: function () {
                    return acquirerAccountInfo;
                },
                init: function () {
                    return init;
                },
                acquirerAccounts: function () {
                    return acquirerAccounts;
                }
            }
        });
        modalInstance.result.then(function () {
            tableReload();
        }, function () {
        });
    };
    $scope.del = function () {
        var idList = [];
        for (var id in $scope.selected) {
            if ($scope.selected[id]) {
                idList.push(id);
            }
        }
        var title = '删除确认';
        var content =
            '<div class="text-center">' +
            '<strong>确定删除这' + idList.length + '条数据吗？</strong>' +
            '</div>';
        var modalInstance = $uibModal.open({
            templateUrl: '/views/common/alert_modal',
            controller: 'alertModalCtrl',
            resolve: {
                title: function () {
                    return title;
                },
                content: function () {
                    return content;
                }
            }
        });
        modalInstance.result.then(function () {
            httpSvc.getData('post', '/acquirer/account/delete', idList).then(function (value) {
                if (value.length === 0) {
                    toaster.pop({
                        type: 'success',
                        title: '收单账户',
                        body: '删除收单账户成功！'
                    });
                    tableReload();
                } else {
                    var toasterBody = '';
                    for (var i = 0; i < value.length; i++) {
                        for (var j = 0; j < acquirerAccounts.length; j++) {
                            if (value[i] === acquirerAccounts[j].id) {
                                toasterBody += acquirerAccounts[j].name;
                                toasterBody += '；';
                                break;
                            }
                        }
                    }
                    toaster.pop({
                        type: 'warning',
                        title: '收单账户',
                        body: '收单账户' + toasterBody + '存在交易订单，无法删除！',
                        timeout: 0
                    });
                }
                $scope.selected = {};
            });
        }, function () {
        });
    };
    $scope.delDisabled = function () {
        for (var id in $scope.selected) {
            if ($scope.selected[id]) {
                return false;
            }
        }
        return true;
    };

    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/acquirer/account/getAll').then(function (value) {
            var i, j, k, currency;
            for (i = 0; i < value.length; i++) {
                value[i]['currencyCN'] = '';
                currency = value[i].currency.replace(/[^a-zA-z,]/g, '').split(',');
                for (j = 0; j < currency.length; j++) {
                    for (k = 0; k < init.currency.length; k++) {
                        if (init.currency[k].firstValue === currency[j]) {
                            value[i]['currencyCN'] += init.currency[k].name + '，';
                            break;
                        }
                    }
                }
                acquirerAccounts = value;
                $scope.acquirerAccountTable.settings({
                    dataset: value
                });
                angular.element('.ibox-content').removeClass('sk-loading');
            }
        });
    }
}

// 收单账户弹窗
function acquirerAccountModalCtrl($scope, $uibModalInstance, $timeout, httpSvc, toaster, type, acquirerAccountInfo, init, acquirerAccounts) {
    $scope.type = type;
    $scope.currency = init.currency;
    $scope.accountStatus = init.status;
    $scope.acquirer = init.acquirer;
    $scope.acquirerAccounts = acquirerAccounts;
    $scope.currencyType = init.currencyType;
    if (type === 1) {
        $scope.acquirerAccountInfo = angular.copy(acquirerAccountInfo);
        $scope.acquirerAccountInfo.currency = $scope.acquirerAccountInfo.currency.replace(/[^a-zA-z,]/g, '').split(',');
        $scope.acquirerAccountInfo.account *= 1;
        $scope.acquirerAccountInfo.isSecondAcquirerStatus += '';
        $scope.acquirerAccountInfo.currencyType += '';
    } else {
        $scope.acquirerAccountInfo = {currency: [], isSecondAcquirerStatus: '1'};
    }
    $scope.exists = function (value, selected) {
        if (value === undefined || selected === undefined) {
            return false;
        }
        return selected.indexOf(value) > -1;
    };
    $scope.toggle = function (value, selected) {
        var index = selected.indexOf(value);
        if (index > -1) {
            selected.splice(index, 1);
        } else {
            selected.push(value);
        }
    };
    $scope.someSelected = function (object) {
        return Object.keys(object).some(function (key) {
            return object[key];
        });
    };
    $scope.nameBlur = $scope.acquirerBlur = $scope.accountBlur = $scope.secondAcquirerIdBlur =
        $scope.statusBlur = $scope.currencyTypeBlur = $scope.secondAccountIdBlur = function ($event, name) {
            verification(name, $event.target)
        };
    $scope.confirm = function (accountInfo, activeForm) {
        switch (activeForm) {
            case 0:
                $scope.activeForm++;
                break;
            case 1:
                $scope.activeForm++;
                break;
            case 2:
                accountInfo.currency = accountInfo.currency.toString();
                if (type === 0) {
                    httpSvc.getData('post', '/acquirer/account/add', accountInfo).then(function (value) {
                        if (value) {
                            toaster.pop({
                                type: 'success',
                                title: '收单账户',
                                body: '添加收单账户成功！'
                            });
                            $uibModalInstance.close();
                        } else {
                            toaster.pop({
                                type: 'error',
                                title: '收单账户',
                                body: '添加收单账户失败！'
                            });
                        }
                    });
                } else {
                    httpSvc.getData('post', '/acquirer/account/update', accountInfo).then(function (value) {
                        if (value) {
                            toaster.pop({
                                type: 'success',
                                title: '收单账户',
                                body: '修改收单账户成功！'
                            });
                            $uibModalInstance.close();
                        } else {
                            toaster.pop({
                                type: 'error',
                                title: '收单账户',
                                body: '修改收单账户失败！'
                            });
                        }
                    });
                }
                break;
        }
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
    $timeout(function () {
        $scope.nextDisabled = function (myForm, activeForm) {
            switch (activeForm) {
                case 0:
                    return myForm.accountName.$error.required || myForm.acquirerId.$error.required ||
                        myForm.currencyType.$error.required || myForm.currency.$error.required ||
                        myForm.status.$error.required;
                case 1:
                    return myForm.account.$error.required;
                case 2:
                    return myForm.$error.required;
            }
        };
    });
}

// 系统日志
function systemLogCtrl($scope, $uibModal, NgTableParams, httpSvc) {
    var oldEndTime = undefined;
    $scope.endTimeDisable = true;
    $scope.format = 'yyyy/MM/dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1,
        maxDate: new Date()
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    $scope.$watch('searchInfo.startTime', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions2.minDate = $scope.searchInfo.startTime;
            $scope.endTimeDisable = false;
            if (oldEndTime !== undefined) {
                $scope.searchInfo.endTime = oldEndTime;
            }
        } else {
            $scope.endTimeDisable = true;
            if ($scope.searchInfo !== undefined) {
                oldEndTime = $scope.searchInfo.endTime;
                $scope.searchInfo.endTime = undefined;
            }
        }
    });
    $scope.$watch('searchInfo.endTime', function (newVal) {
        if (newVal !== undefined && newVal !== null) {
            $scope.dateOptions1.maxDate = $scope.searchInfo.endTime;
        } else {
            $scope.dateOptions1.maxDate = new Date();
        }
    });

    $scope.search = function (searchInfo) {
        $scope.logTable.page(1);
        $scope.logTable.reload();
    };
    $scope.reset = function () {
        $scope.searchInfo = {};
        $scope.logTable.page(1);
        $scope.logTable.reload();
    };
    httpSvc.getData('post', '/system/getConstantByGroupName', JSON.stringify('Log')).then(function (value) {
        $scope.logType = value;
        $scope.logTable = new NgTableParams({}, {
            getData: function (params) {
                angular.element('.ibox-content').addClass('sk-loading');
                return httpSvc.getData('post', '/system/getSystemLog', {
                    pageNum: params.page(),
                    pageSize: params.count(),
                    orderBy: params.sorting(),
                    logSearch: $scope.searchInfo
                }).then(function (value) {
                    var i, j;
                    params.total(value.total);
                    for (i = 0; i < value.rows.length; i++) {
                        value.rows[i].type += '';
                        for (j = 0; j < $scope.logType.length; j++) {
                            if (value.rows[i].type === $scope.logType[j].firstValue) {
                                value.rows[i]['typeCN'] = $scope.logType[j].name;
                            }
                        }
                    }
                    angular.element('.ibox-content').removeClass('sk-loading');
                    return value.rows;
                });
            }
        });
    });
    $scope.showModal = function (logInfo) {
        var modalSize = '';
        switch (logInfo.type) {
            case '9':
                modalSize = 'lg';
                break;
        }
        var modalInstance = $uibModal.open({
            templateUrl: '/views/system_settings/system_log_modal',
            controller: 'systemLogModalCtrl',
            size: modalSize,
            resolve: {
                logInfo: function () {
                    return logInfo;
                }
            }
        });
        modalInstance.result.then(function () {

        }, function () {

        });
    };
}

// 系统日志弹窗
function systemLogModalCtrl($scope, $uibModalInstance, logInfo) {
    $scope.logInfo = angular.copy(logInfo);
    // $scope.messageJson = null;
    if (logInfo.type !== '0' && logInfo.type !== '9') {
        // 将超过15位的数字替换成字符串再转json对象
        $scope.logInfo.messageJson = angular.fromJson($scope.logInfo.message.replace(/(\d{15,})/g, '"$1"'));
    }
    $scope.cancel = function () {
        $uibModalInstance.dismiss()
    };
}

// 商户管理
function merchantMgmtCtrl($scope, $filter, $uibModal, $state, NgTableParams, httpSvc, toaster) {
    var oldEndTime = undefined;
    $scope.selected = {};
    $scope.format = 'yyyy/MM/dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    $scope.search = function (searchInfo) {
        // searchInfo.startTime = Date.parse(searchInfo.startTime);
        // searchInfo.endTime = Date.parse(searchInfo.endTime);
        console.log(searchInfo);
        angular.extend($scope.merchantTable.filter(), searchInfo);
    };
    $scope.reset = function () {
        $scope.searchInfo = {};
        $scope.merchantTable.filter({});
    };
    $scope.del = function () {
        httpSvc.getData('post', '/merchant/deleteMerchantById', JSON.stringify($scope.selected.id)).then(function (value) {
            if (value) {
                $scope.selected = {};
                toaster.pop({
                    type: 'success',
                    title: '商户管理',
                    body: '删除商户成功！'
                });
                tableReload();
            } else {
                toaster.pop({
                    type: 'success',
                    title: '商户管理',
                    body: '改商户存在交易无法删除！'
                });
            }
        });
    };
    $scope.delDisabled = function () {
        return $scope.selected.id === undefined;
    };
    var init;
    var merchantSetting, merchantInfo, merchantPay = [];
    var merchants = [];
    httpSvc.getData('post', '/merchant/getMgmtInit').then(function (value) {
        $scope.merchantCategory = value.merchantCategory;
        $scope.businessType = value.businessType;
        $scope.merchantStatus = value.merchantStatus;
        init = value;
        httpSvc.getData('post', '/merchant/getAllMerchantInfoForView').then(function (value1) {
            var i, j, k;
            merchantSetting = value1.merchantSetting;
            merchantInfo = value1.merchantInfo;
            merchantPay = value1.merchantPay;
            for (i = 0; i < merchantInfo.length; i++) {
                var merchant = {
                    merId: merchantInfo[i].id,
                    category: merchantInfo[i].category,
                    refType: null,
                    salesmanName: null,
                    startTime: null,
                    endTime: null,
                    status: null,
                    merchantSetting: null,
                    merchantInfo: null,
                    merchantPay: null
                };
                for (j = 0; j < merchantSetting.length; j++) {
                    if (merchantSetting[j].id === merchantInfo[i].id) {
                        merchant.merchantSetting = merchantSetting[j];
                        merchant.refType = merchantSetting[j].refType;
                        merchant.salesmanName = merchantSetting[j].salesmanName;
                        merchant.startTime = merchantSetting[j].startTime;
                        merchant.endTime = merchantSetting[j].endTime;
                        break;
                    }
                }
                for (j = 0; j < merchantPay.length; j++) {
                    if (merchantPay[j].refId === merchantInfo[i].id) {
                        merchant.merchantPay = merchantPay[j];
                        merchant.status = merchantPay[j].status;
                        break;
                    }
                }
                merchant.merchantInfo = merchantInfo[i];
                merchants.push(merchant);
            }
            $scope.merchantTable = new NgTableParams({}, {
                filterOptions: {filterFn: dateRangeFilter},
                dataset: merchants
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    });
    $scope.statusChange = function ($event, row) {
        var status;
        angular.element($event.target).hasClass('active') ? status = 1 : status = 0;
        httpSvc.getData('post', '/merchant/updateMerchantPay', {
            id: row.merchantPay.id,
            status: status
        }).then(function (value) {
            if (value) {
                toaster.pop({
                    type: 'success',
                    title: '商户管理',
                    body: '更新商户状态成功！'
                });
                tableReload();
            } else {
                toaster.pop({
                    type: 'error',
                    title: '商户管理',
                    body: '更新商户状态失败！'
                });
            }
        });
    };
    // 跳转商户详情页面
    $scope.goMerchantInfo = function (merchantInfo) {
        $state.go('base_view.business.merchant_info', {
            merchant: merchantInfo,
            goType: 1,
            merchantCategory: $scope.merchantCategory,
            businessType: $scope.businessType
        });
    };
    $scope.goMerchantSetting = function (merchantInfo) {
        $state.go('base_view.business.merchant_setting', {
            merchant: merchantInfo,
            goType: 1
        });
    };
    $scope.goMerchantPay = function (merchantInfo) {
        $state.go('base_view.business.merchant_pay', {
            merchant: merchantInfo,
            goType: 1
        });
    };
    $scope.goMerchantUser = function (merchantInfo) {
        $state.go('base_view.business.merchant_user', {
            merchant: merchantInfo
        });
    };

    function tableReload() {
        merchants = [];
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/merchant/getAllMerchantInfoForView').then(function (value) {
            var i, j, k;
            merchantSetting = value.merchantSetting;
            merchantInfo = value.merchantInfo;
            merchantPay = value.merchantPay;
            for (i = 0; i < merchantInfo.length; i++) {
                var merchant = {
                    merId: merchantInfo[i].id,
                    category: merchantInfo[i].category,
                    refType: null,
                    salesmanName: null,
                    startTime: null,
                    endTime: null,
                    status: null,
                    merchantSetting: null,
                    merchantInfo: null,
                    merchantPay: null
                };
                /*for (j = 0; j < init.merchantCategory.length; j++) {
                    if (init.merchantCategory[j].firstValue === merchantInfo[i].category) {
                        merchantInfo[i]['categoryCN'] = init.merchantCategory[j].name;
                        break;
                    }
                }*/
                for (j = 0; j < merchantSetting.length; j++) {
                    if (merchantSetting[j].id === merchantInfo[i].id) {
                        /*for (k = 0; k < init.businessType.length; k++) {
                            if (init.businessType[k].firstValue === (merchantSetting[j].refType += '')) {
                                merchantSetting[j]['refTypeCN'] = init.businessType[k].name;
                                break;
                            }
                        }*/
                        merchant.merchantSetting = merchantSetting[j];
                        merchant.refType = merchantSetting[j].refType;
                        merchant.salesmanName = merchantSetting[j].salesmanName;
                        merchant.startTime = merchantSetting[j].startTime;
                        merchant.endTime = merchantSetting[j].endTime;
                        break;
                    }
                }
                for (j = 0; j < merchantPay.length; j++) {
                    if (merchantPay[j].refId === merchantInfo[i].id) {
                        merchant.merchantPay = merchantPay[j];
                        merchant.status = merchantPay[j].status;
                        break;
                    }
                }
                merchant.merchantInfo = merchantInfo[i];
                merchants.push(merchant);
            }
            $scope.merchantTable.settings({
                dataset: merchants
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
    // 自定义ng-Table Filter
    function dateRangeFilter(data, filterValues/*, comparator*/) {
        if (filterValues.startTime == null && filterValues.endTime == null) {
            return $filter('filter')(data, filterValues);
        } else {
            var start = null;
            var end = null;
            if (filterValues.startTime == null && filterValues.endTime != null) {
                end = filterValues.endTime;
                delete filterValues.endTime;
            } else if (filterValues.startTime != null && filterValues.endTime == null) {
                start = filterValues.startTime;
                delete filterValues.startTime;
            } else {
                start = filterValues.startTime;
                end = filterValues.endTime;
                delete filterValues.startTime;
                delete filterValues.endTime;
            }
            return $filter('filter')(data, filterValues).filter(function (item) {
                if (start == null && end != null) {
                    return end >= item.merchantSetting.endTime;
                } else if (start != null && end == null) {
                    return start <= item.merchantSetting.startTime;
                } else {
                    return start <= item.merchantSetting.startTime && end >= item.merchantSetting.endTime;
                }
            });
        }
    }
}

// 商户信息页面
function merchantInfoCtrl($scope, $state, $stateParams, httpSvc, toaster, FileUploader) {
    var certificateImgUrl = [];
    if ($stateParams.goType === null) {
        if ($stateParams.merchant === null) {
            $scope.merchant = {merchantInfo: null, merchantSetting: null, merchantPay: {email: null}};
            $scope.certificateImgUrl = [];
        } else {
            $scope.merchant = $stateParams.merchant;
        }
        httpSvc.getData('post', '/merchant/getMgmtInit').then(function (value) {
            $scope.merchantCategory = value.merchantCategory;
            $scope.businessType = value.businessType;
        });
    } else {
        $scope.merchant = angular.copy($stateParams.merchant);
        if ($scope.merchant.merchantInfo.certificate != null && $scope.merchant.merchantInfo.certificate.trim() !== '') {
            $scope.certificateImgUrl = $scope.merchant.merchantInfo.certificate.split(',');
            certificateImgUrl = angular.copy(certificateImgUrl);
        } else {
            $scope.certificateImgUrl = [];
        }
    }
    $scope.isMerchantIdExist = false;
    $scope.goType = $stateParams.goType;
    $scope.merchantCategory = $stateParams.merchantCategory;
    $scope.businessType = $stateParams.businessType;
    $scope.merIdBlur = function ($event, value) {
        if (!verification(value, $event.target)) {
            httpSvc.getData('post', '/merchant/isMerchantIdExist', JSON.stringify(value)).then(function (value) {
                if (value) {
                    verification(undefined, $event.target);
                    $scope.isExist = true;
                } else {
                    $scope.isMerchantIdExist = false;
                    $scope.isExist = false;
                }
            });
        }
    };
    $scope.uploader = new FileUploader({
        url: '/merchant/uploadMerchantCertificate'
    });
    $scope.uploader.onBeforeUploadItem = function (item) {
        item.formData.push({merchantId: $scope.merchant.merchantInfo.id});
    };
    /*$scope.uploader.onAfterAddingFile = function () {
        $scope.uploader.uploadAll();
    };*/
    $scope.uploader.onAfterAddingAll = function () {
        $scope.uploader.uploadAll();
    };
    $scope.uploader.onSuccessItem = function (item, response, status, headers) {
        $scope.certificateImgUrl.push(response);
    };
    $scope.uploader.onCompleteAll = function () {
        $scope.uploader.clearQueue();
    };
    /*$scope.uploader.filters.push({
        name: 'imageFilter',
        fn: function (item, options) {
            var type = '|' + item.type.slice(item.type.lastIndexOf('/') + 1) + '|';
            if ('|jpg|png|jpeg|bmp|gif|'.indexOf(type) !== -1) {
                $scope.uploader.clearQueue();
                return true;
            }
            return false;
        }
    });*/
    httpSvc.getData('post', '/system/getAreaInfoByCountryCode', JSON.stringify('CHN')).then(function (value) {
        $scope.provinceInfo = value;
        $scope.$watch('merchant.merchantInfo.province', function (newVal) {
            if (newVal !== undefined) {
                for (var i = 0; i < $scope.provinceInfo.length; i++) {
                    if ($scope.provinceInfo[i].id === newVal) {
                        $scope.cityInfo = $scope.provinceInfo[i].childArea;
                        break;
                    }
                }
            }
        });
        $scope.$watch('merchant.merchantInfo.city', function (newVal) {
            if (newVal !== undefined && $scope.cityInfo !== undefined) {
                for (var i = 0; i < $scope.cityInfo.length; i++) {
                    if ($scope.cityInfo[i].id === newVal) {
                        $scope.areaInfo = $scope.cityInfo[i].childArea;
                        break;
                    }
                }
            }
        });
        $scope.provinceChange = function () {
            $scope.merchant.merchantInfo.city = undefined;
            $scope.merchant.merchantInfo.area = undefined;
        };
        $scope.cityChange = function () {
            $scope.merchant.merchantInfo.area = undefined;
        };
    });
    var oldEndDate = null;
    $scope.endDateDisable = true;
    $scope.format = 'yyyy/MM/dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };
    $scope.confirmDisabled = function (myForm) {
        if ($stateParams.goType === null && $stateParams.merchant === null) {
            if ($scope.merchant.merchantInfo == null) {
                return true;
            }
            return !myForm.$valid || $scope.isMerchantIdExist;
        } else if ($stateParams.goType === null && $stateParams.merchant !== null) {
            return !myForm.$valid || $scope.isMerchantIdExist;
        } else {
            return (angular.equals($scope.merchant.merchantInfo, $stateParams.merchant.merchantInfo) &&
                angular.equals($scope.merchant.merchantPay, $stateParams.merchant.merchantPay) &&
                angular.equals($scope.merchant.merchantSetting, $stateParams.merchant.merchantSetting) &&
                angular.equals(certificateImgUrl, $scope.certificateImgUrl)) || !myForm.$valid;
        }
    };
    $scope.confirm = function () {
        if ($scope.merchant.merchantPay.email === undefined ||
            $scope.merchant.merchantPay.email === null ||
            $scope.merchant.merchantPay.email === '') {
            $scope.merchant.merchantPay.email = $scope.merchant.merchantInfo.email;
        }
        $scope.merchant.merchantInfo.certificate = $scope.certificateImgUrl.toString();

        if ($stateParams.goType === null && $stateParams.merchant === null) {
            $scope.merchant.merchantPay.refId = $scope.merchant.merchantSetting.id = $scope.merchant.merchantInfo.id;
            if ($scope.uploader.queue.length == null || $scope.uploader.queue.length === 0) {
                $state.go('base_view.business.merchant_setting', {
                    merchant: $scope.merchant
                });
            }
            /*httpSvc.getData('post', '/merchant/addMerchant', $scope.merchant).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '商户管理',
                        body: '商户开通成功！'
                    });
                    $scope.uploader.uploadAll();
                    $state.go('base_view.business.merchant_mgmt');
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '商户管理',
                        body: '商户开通失败！'
                    });
                }
            });*/
        } else if ($stateParams.goType === null && $stateParams.merchant !== null) {
            $state.go('base_view.business.merchant_setting', {
                merchant: $scope.merchant
            });
        } else {
            httpSvc.getData('post', '/merchant/updateMerchant', $scope.merchant).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '商户管理',
                        body: '更新商户信息成功！'
                    });
                    $state.go('base_view.business.merchant_mgmt');
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '商户管理',
                        body: '更新商户信息失败！'
                    });
                }
            });
        }
    };
    $scope.cancel = function () {
        $state.go('base_view.business.merchant_mgmt');
    };
}

// 商户设置页面
function merchantSettingCtrl($scope, $state, $stateParams, httpSvc, toaster) {
    $scope.goType = $stateParams.goType;
    if ($stateParams.merchant !== null) {
        $scope.merchant = angular.copy($stateParams.merchant);
        httpSvc.getData('post', '/merchant/getMerchantSettingInit').then(function (value) {
            $scope.level = value.level;
            $scope.automaticRenewal = value.automaticRenewal;
            $scope.trackSetting = value.trackSetting;
            $scope.trackAudit = value.trackAudit;
            $scope.correctDistribute = value.correctDistribute;
            $scope.businessType = value.businessType;
            $scope.currency = value.currency;
        });
        $scope.confirmDisabled = function (myForm) {
            return !myForm.$valid;
        };
        $scope.confirm = function () {
            if ($stateParams.goType === null) {
                $state.go('base_view.business.merchant_pay', {
                    merchant: $scope.merchant
                });
            } else {
                httpSvc.getData('post', '/merchant/updateMerchantSetting', $scope.merchant.merchantSetting).then(function (value) {
                    if (value) {
                        toaster.pop({
                            type: 'success',
                            title: '商户管理',
                            body: '更新商户设置成功！'
                        });
                        $state.go('base_view.business.merchant_mgmt');
                    } else {
                        toaster.pop({
                            type: 'error',
                            title: '商户管理',
                            body: '更新商户设置失败！'
                        });
                    }
                });
            }
        };
        $scope.cancel = function () {
            if ($stateParams.goType === null) {
                $state.go('base_view.business.merchant_info', {
                    merchant: $scope.merchant
                });
            } else {
                $state.go('base_view.business.merchant_mgmt');
            }
        }
    } else {
        $state.go('base_view.business.merchant_mgmt');
    }
}

// 商户支付属性页面
function merchantPayCtrl($scope, $state, $stateParams, httpSvc, toaster) {
    $scope.goType = $stateParams.goType;
    if ($stateParams.merchant !== null) {
        $scope.merchantPay = angular.copy($stateParams.merchant.merchantPay);
        if ($scope.merchantPay.merchantRateList === undefined) {
            $scope.merchantPay.merchantRateList = [];
        }
        // 初始化支持币种
        if ($scope.merchantPay.currency === undefined || $scope.merchantPay.currency.length === 0) {
            $scope.merchantPay.currency = [];
        } else {
            $scope.merchantPay.currency = $scope.merchantPay.currency.replace(/[^a-zA-z,]/g, '').split(',');
        }
        // 初始化支付方式
        if ($scope.merchantPay.payMode === undefined || $scope.merchantPay.payMode.length === 0) {
            $scope.merchantPay.payMode = [];
        } else {
            $scope.merchantPay.payMode = $scope.merchantPay.payMode.replace(/[^a-zA-z,]/g, '').split(',');
        }
        var init;
        $scope.payModeTable = {};
        $scope.exists = function (value, selected) {
            if (value === undefined || selected === undefined) {
                return false;
            }
            return selected.indexOf(value) > -1;
        };
        $scope.toggle = function (value, selected) {
            var index = selected.indexOf(value);
            if (index > -1) {
                selected.splice(index, 1);
            } else {
                selected.push(value);
            }
        };
        // 根据支付方式勾选内容变化显示相应的支付方式信息以及对商户支付类型数组的操作
        $scope.payModeToggle = function (payMode, selected) {
            var index = selected.indexOf(payMode);
            if (index > -1) {
                selected.splice(index, 1);
                $scope.payModeTable[payMode].show = false;
            } else {
                selected.push(payMode);
                $scope.payModeTable[payMode].show = true;
            }
        };
        $scope.someSelected = function (object) {
            return Object.keys(object).some(function (key) {
                return object[key];
            });
        };
        $scope.acquirerChange = function (object, value, second) {
            var account = [];
            angular.forEach(init.acquirerAccount, function (val) {
                if (val.acquirerId === value) {
                    account.push(val);
                }
            });
            if (second) {
                object.secondAcquirerAccount = account;
            } else {
                object.acquirerAccount = account;
            }
        };
        // 初始化显示信息并获取商户汇率
        httpSvc.getData('post', '/merchant/getMerchantPayInit').then(function (value) {
            init = value;
            $scope.currency = value.currency;
            $scope.encrypt = value.encrypt;
            $scope.status = value.status;
            $scope.payMode = value.payMode;
            $scope.interfaceType = value.interfaceType;
            $scope.acquirer = value.acquirer;
            // 初始化payModeTable
            angular.forEach($scope.payMode, function (value1) {
                // 初始化选择收单账户对象
                for (var i = 0; i < init[value1.firstValue].length; i++) {
                    init[value1.firstValue][i].id = null;
                    init[value1.firstValue][i].acquirerAccount = [];
                    init[value1.firstValue][i].secondAcquirerAccount = [];
                }
                // 将支付方式放入payModeTable内
                $scope.payModeTable[value1.firstValue] = value1;
                // 判断商户支持支付方式，若支持显示
                $scope.payModeTable[value1.firstValue].show = $scope.merchantPay.payMode.indexOf(value1.firstValue) > -1;
                // 初始化支付类型
                $scope.payModeTable[value1.firstValue].payType = init[value1.firstValue];
            });
            if ($stateParams.goType === 1) {
                // 获取商户汇率
                httpSvc.getData('post', '/merchant/getMerchantRateByRefIdAndRefType', {
                    refId: $scope.merchantPay.refId,
                    refType: 1
                }).then(function (value1) {
                    if (value1.length > 0) {
                        organizeRateData(value1);
                    }
                });
            } else if ($scope.merchantPay.merchantRateList.length > 0) {
                organizeRateData($scope.merchantPay.merchantRateList);
            }
        });
        $scope.confirmDisabled = function (myForm) {
            return !myForm.$valid;
        };
        $scope.confirm = function () {
            organizeData();
            var obj;
            var url;
            if ($scope.goType === null) {
                url = '/merchant/addMerchant';
                $scope.merchantPay.ref_type = 1;
                $stateParams.merchant.merchantPay = $scope.merchantPay;
                obj = $stateParams.merchant;
            } else {
                url = '/merchant/updateMerchantPay';
                obj = $scope.merchantPay;
            }
            httpSvc.getData('post', url, obj).then(function (value) {
                if (value) {
                    if ($scope.merchantPay.merchantRateList.length > 0) {
                        httpSvc.getData('post', '/merchant/updateMerchantRateByList', $scope.merchantPay.merchantRateList).then(function (value1) {
                            if (value1) {
                                toaster.pop({
                                    type: 'success',
                                    title: '商户管理',
                                    body: $scope.goType === null ? '新增商户成功！' : '更新商户扣率成功！'
                                });
                                $state.go('base_view.business.merchant_mgmt');
                            } else {
                                toaster.pop({
                                    type: 'error',
                                    title: '商户管理',
                                    body: $scope.goType === null ? '新增商户失败！' : '更新商户扣率失败！'
                                });
                            }
                        });
                    } else {
                        toaster.pop({
                            type: 'success',
                            title: '商户管理',
                            body: $scope.goType === null ? '新增商户成功！' : '更新商户扣率成功！'
                        });
                        $state.go('base_view.business.merchant_mgmt');
                    }
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '商户管理',
                        body: $scope.goType === null ? '新增商户失败！' : '更新商户扣率失败！'
                    });
                }
            });
        };
        $scope.cancel = function () {
            if ($stateParams.goType === null) {
                organizeData();
                $stateParams.merchant.merchantPay = $scope.merchantPay;
                $state.go('base_view.business.merchant_setting', {
                    merchant: $stateParams.merchant
                });
            } else {
                $state.go('base_view.business.merchant_mgmt');
            }
        }
    } else {
        $state.go('base_view.business.merchant_mgmt');
    }

    function organizeData() {
        angular.forEach($scope.merchantPay.payMode, function (value) {
            for (var i = 0; i < $scope.payModeTable[value].payType.length; i++) {
                if ($scope.payModeTable[value].payType[i].rate !== undefined) {
                    $scope.payModeTable[value].payType[i].refId = $scope.merchantPay.refId;
                    // refType：1商户扣率，；2，商户网址扣率
                    $scope.payModeTable[value].payType[i].refType = 1;
                    $scope.payModeTable[value].payType[i].payMode = value;
                    $scope.payModeTable[value].payType[i].payType = $scope.payModeTable[value].payType[i].firstValue;
                    $scope.payModeTable[value].payType[i].bailCycle = $scope.merchantPay.bailCycle;
                    $scope.payModeTable[value].payType[i].bailRate = $scope.merchantPay.bailRate;
                    $scope.merchantPay.merchantRateList.push($scope.payModeTable[value].payType[i]);
                }
            }
        });
        $scope.merchantPay.currency = $scope.merchantPay.currency.toString();
        $scope.merchantPay.payMode = $scope.merchantPay.payMode.toString();
    }

    function organizeRateData(value) {
        $scope.merchantPay.bailCycle = value[0].bailCycle;
        $scope.merchantPay.bailRate = value[0].bailRate;
        // merchantPayOld = angular.copy($scope.merchantPay);
        // 将商户汇率对象放入payModeTable显示
        angular.forEach($scope.payModeTable, function (obj, key) {
            for (var i = 0; i < value.length; i++) {
                if (value[i].payMode === key) {
                    for (var j = 0; j < obj.payType.length; j++) {
                        if (obj.payType[j].firstValue === value[i].payType) {
                            angular.extend(obj.payType[j], value[i]);
                            $scope.acquirerChange(obj.payType[j], obj.payType[j].acquirerId, false);
                            $scope.acquirerChange(obj.payType[j], obj.payType[j].secondAcquirerId, true);
                            break;
                        }
                    }
                }
            }
        });
    }
}

// 商户用户管理
function merchantUserMgmtCtrl($scope, $state, $stateParams, $uibModal, toaster, NgTableParams, httpSvc) {
    if ($stateParams.merchant !== null) {
        $scope.delDisabled = true;
        $scope.selected = {};
        $scope.statusChange = function (row) {
            httpSvc.getData('post', '/merchant/updateMerchantUser', {
                id: row.id,
                available: !row.available
            }).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '商户用户管理',
                        body: '更新用户状态成功！'
                    });
                    tableReload();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '商户用户管理',
                        body: '更新用户状态失败！'
                    });
                }
            })
        };
        httpSvc.getData('post', '/merchant/getMerchantUserByMerchantId', JSON.stringify($stateParams.merchant.merId)).then(function (value) {
            $scope.merchantUserTable = new NgTableParams({}, {
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
        $scope.showModal = function () {
            var modalInstance = $uibModal.open({
                templateUrl: '/views/business/merchant_user_modal',
                controller: 'merchantUserModalCtrl',
                resolve: {
                    userInfo: function () {
                        return null;
                    },
                    // 0新增；1修改信息，2修改密码
                    type: function () {
                        return 0;
                    },
                    merchantId: function () {
                        return $stateParams.merchant.merId;
                    }
                }
            });
            modalInstance.result.then(function () {
                tableReload();
            }, function () {
                // tableReload();
            });
        };
        $scope.edit = function (user, type) {
            var modalInstance = $uibModal.open({
                templateUrl: '/views/business/merchant_user_modal',
                controller: 'merchantUserModalCtrl',
                resolve: {
                    userInfo: function () {
                        return user;
                    },
                    // 0新增；1修改信息，2修改密码
                    type: function () {
                        return type;
                    },
                    merchantId: function () {
                        return $stateParams.merchant.merId;
                    }
                }
            });
            modalInstance.result.then(function () {
                tableReload();
            }, function () {
            });
        };
        $scope.del = function () {
            var idList = [];
            for (var id in $scope.selected) {
                if ($scope.selected[id]) {
                    idList.push(id);
                }
            }
            httpSvc.getData('post', '/merchant/deleteMerchantUser', idList).then(function (value) {
                if (value) {
                    $scope.selected = {};
                    toaster.pop({
                        type: 'success',
                        title: '用户管理',
                        body: '删除用户成功！'
                    });
                    tableReload();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '用户管理',
                        body: '删除用户失败！'
                    });
                }
            });
        };
        $scope.delDisabled = function () {
            for (var id in $scope.selected) {
                if ($scope.selected[id]) {
                    return false;
                }
            }
            return true;
        };

        function tableReload() {
            angular.element('.ibox-content').addClass('sk-loading');
            httpSvc.getData('post', '/merchant/getMerchantUserByMerchantId', JSON.stringify($stateParams.merchant.merId)).then(function (value) {
                $scope.merchantUserTable.settings({
                    dataset: value
                });
                angular.element('.ibox-content').removeClass('sk-loading');
            });
        }
    } else {
        $state.go('base_view.business.merchant_mgmt');
    }
}

// 商户用户管理弹窗
function merchantUserModalCtrl($scope, $uibModalInstance, httpSvc, toaster, type, userInfo, merchantId) {
    if (type !== 0) {
        $scope.userInfo = angular.copy(userInfo);
    }
    $scope.nameValid = false;
    $scope.passwordValid = false;
    $scope.type = type;
    $scope.userNameBlur = function ($event, userName) {
        if (!verification(userName, $event.target)) {
            httpSvc.getData('post', '/merchant/isMerchantUserExist', {
                userName: userName,
                belongto: merchantId
            }).then(function (value) {
                if (value) {
                    verification(null, $event.target);
                } else {
                    $scope.nameValid = true;
                }
            });
        } else {
            $scope.nameValid = false;
        }
    };
    $scope.passwordBlur = function ($event, password) {
        if (password === undefined || password.length < 6) {
            verification(undefined, $event.target);
        } else {
            verification(password, $event.target);
        }
    };
    $scope.passwordBBlur = function ($event, passwordB, password) {
        if (passwordB === undefined || passwordB !== password) {
            $scope.passwordValid = !verification(undefined, $event.target);
        } else {
            $scope.passwordValid = !verification(passwordB, $event.target);
        }
    };
    $scope.phoneBlur = $scope.emailBlur = function ($event, value) {
        verification(value, $event.target)
    };
    $scope.confirmDisabled = function (myForm) {
        switch (type) {
            case 0:
                return !myForm.$valid || !$scope.nameValid || !$scope.passwordValid;
            case 1:
                return !myForm.userName.$valid || !myForm.mobile.$valid || !myForm.email.$valid;
            case 2:
                return !$scope.passwordValid;
        }
    };
    $scope.confirm = function () {
        if (type === 0) {
            $scope.userInfo.belongto = merchantId;
            httpSvc.getData('post', '/merchant/addMerchantUser', $scope.userInfo).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '商户用户管理',
                        body: '新增用户成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '商户用户管理',
                        body: '新增用户失败！'
                    });
                }
            });
        } else {
            httpSvc.getData('post', '/merchant/updateMerchantUser', $scope.userInfo).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '商户用户管理',
                        body: '更新用户成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '商户用户管理',
                        body: '更新用户失败！'
                    });
                }
            });
        }
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    }
}

// 商户网址管理
function merchantWebSiteCtrl($scope, $uibModal, $state, NgTableParams, httpSvc, toaster) {
    var init;
    var webSite;
    $scope.selected = {};
    httpSvc.getData('post', '/merchant/webSite/getInit').then(function (value) {
        init = value;
        $scope.merchantInfo = value.merchantInfo;
        $scope.merchantWebSite = value.merchantWebSite;
        $scope.merchantWebsiteProType = value.merchantWebsiteProType;
        $scope.industryType = value.industryType;
        $scope.webSiteStatus = value.webSiteStatus;
        httpSvc.getData('post', '/merchant/getAllMerchantWebSite').then(function (value1) {
            $scope.siteUrls = webSite = value1;
            $scope.webSiteTable = new NgTableParams({}, {
                dataset: value1
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    });
    $scope.$watch('searchInfo.merId', function (newVal) {
        if (webSite !== undefined) {
            if (newVal !== undefined) {
                var urls = [];
                for (var i = 0; i < webSite.length; i++) {
                    if (webSite[i].merId === newVal) {
                        urls.push(webSite[i]);
                    }
                }
                $scope.siteUrls = urls;
            } else {
                $scope.siteUrls = webSite;
            }
        }
    });
    $scope.search = function (searchInfo) {
        angular.extend($scope.webSiteTable.filter(), searchInfo);
    };
    $scope.reset = function () {
        $scope.searchInfo = {};
        $scope.webSiteTable.filter({});
    };
    $scope.showModal = $scope.edit = function (type, webSiteInfo) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/business/merchant_web_site_modal',
            controller: 'merchantWebSiteModalCtrl',
            resolve: {
                type: function () {
                    return type;
                },
                webSiteInfo: function () {
                    return webSiteInfo;
                },
                init: function () {
                    return init;
                }
            }
        });
        modalInstance.result.then(function () {
            tableReload();
        }, function () {

        });
    };
    $scope.statusChange = function ($event, webSiteInfo) {
        if (webSiteInfo.status === 2) {
            $scope.edit(webSiteInfo.status, webSiteInfo);
        } else {
            var status = webSiteInfo.status === 0 ? 1 : 0;
            httpSvc.getData('post', '/merchant/webSite/update', {
                id: webSiteInfo.id,
                status: status
            }).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '域名管理',
                        body: '更新域名成功！'
                    });
                    tableReload();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '域名管理',
                        body: '更新域名失败！'
                    });
                }
            });
        }
    };
    $scope.del = function () {
        var idList = [];
        for (var id in $scope.selected) {
            if ($scope.selected[id]) {
                idList.push(id);
            }
        }
        httpSvc.getData('post', '/merchant/webSite/delete', idList).then(function (value) {
            if (value.length === 0) {
                toaster.pop({
                    type: 'success',
                    title: '域名管理',
                    body: '删除域名成功！'
                });
            } else {
                var toasterBody = '';
                for (var i = 0; i < value.length; i++) {
                    for (var j = 0; j < webSite.length; j++) {
                        if (value[i] === webSite[j].id) {
                            toasterBody += webSite[j].siteUrl;
                            toasterBody += '；';
                            break;
                        }
                    }
                }
                toaster.pop({
                    type: 'warning',
                    title: '域名管理',
                    body: '域名 ' + toasterBody + ' 存在订单，无法删除！',
                    timeout: 0
                });
            }
            $scope.selected = {};
            tableReload();
        });
    };
    $scope.delDisabled = function () {
        for (var id in $scope.selected) {
            if ($scope.selected[id]) {
                return false;
            }
        }
        return true;
    };
    $scope.goMerchantWebSiteRate = function (webSiteInfo) {
        $state.go('base_view.business.merchant_web_site_rate', {
            webSiteInfo: webSiteInfo
        })
    };

    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/merchant/getAllMerchantWebSite').then(function (value) {
            $scope.siteUrls = webSite = value;
            $scope.webSiteTable.settings({
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
}

// 商户网址弹窗
function merchantWebSiteModalCtrl($scope, $uibModalInstance, httpSvc, type, webSiteInfo, init, toaster) {
    $scope.type = type;
    $scope.merchantInfo = init.merchantInfo;
    $scope.merchantWebSite = init.merchantWebSite;
    $scope.merchantWebsiteProType = init.merchantWebsiteProType;
    $scope.industryType = init.industryType;
    $scope.webSiteStatus = init.webSiteStatus;
    if (type !== 0) {
        $scope.webSiteInfo = webSiteInfo;
    }
    $scope.cancel = function () {
        $uibModalInstance.dismiss()
    };
    $scope.merIdBlur = $scope.statusBlur = $scope.industryIdBlur = $scope.productTypeIdBlur = function ($event, value) {
        verification(value, $event.target);
    };
    $scope.siteUrlBlur = function ($event, siteUrl) {
        if (!verification(siteUrl, $event.target)) {
            httpSvc.getData('post', '/merchant/webSite/isExist', JSON.stringify(siteUrl)).then(function (value) {
                if (value) {
                    angular.element($event.target).parent().removeClass('has-success');
                    angular.element($event.target).parent().addClass('has-error');
                    $scope.siteUrlExist = true;
                } else {
                    angular.element($event.target).parent().removeClass('has-error');
                    angular.element($event.target).parent().addClass('has-success');
                    $scope.siteUrlExist = false;
                }
            });
        }
    };
    $scope.confirm = function (webSiteInfo) {
        if (type === 0) {
            httpSvc.getData('post', '/merchant/webSite/add', webSiteInfo).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '域名管理',
                        body: '添加域名成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '域名管理',
                        body: '添加域名失败！'
                    });
                }
            });
        } else {
            if (type === 2) {
                webSiteInfo.status = 0;
            }
            httpSvc.getData('post', '/merchant/webSite/update', webSiteInfo).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '域名管理',
                        body: '更新域名成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '域名管理',
                        body: '更新域名失败！'
                    });
                }
            });
        }
    };
}

// 商户网址扣率
function merchantWebSiteRateCtrl($scope, $state, $stateParams, httpSvc, toaster) {
    if ($stateParams.webSiteInfo !== null) {
        httpSvc.getData('post', '/merchant/getMerchantPayByWebSiteId', JSON.stringify($stateParams.webSiteInfo.merId)).then(function (value) {
            $scope.merchantPay = value;
            if ($scope.merchantPay.merchantRateList === undefined) {
                $scope.merchantPay.merchantRateList = [];
            }
            // 初始化支持币种
            if ($scope.merchantPay.currency === undefined) {
                $scope.merchantPay.currency = [];
            } else {
                $scope.merchantPay.currency = $scope.merchantPay.currency.replace(/[^a-zA-z,]/g, '').split(',');
            }
            // 初始化支付方式
            if ($scope.merchantPay.payMode === undefined) {
                $scope.merchantPay.payMode = [];
            } else {
                $scope.merchantPay.payMode = $scope.merchantPay.payMode.replace(/[^a-zA-z,]/g, '').split(',');
            }
            var init;
            $scope.payModeTable = {};
            $scope.exists = function (value, selected) {
                if (value === undefined || selected === undefined) {
                    return false;
                }
                return selected.indexOf(value) > -1;
            };
            $scope.toggle = function (value, selected) {
                var index = selected.indexOf(value);
                if (index > -1) {
                    selected.splice(index, 1);
                } else {
                    selected.push(value);
                }
                console.log($scope.merchantPay);
            };
            // 根据支付方式勾选内容变化显示相应的支付方式信息以及对商户支付类型数组的操作
            $scope.payModeToggle = function (payMode, selected) {
                var index = selected.indexOf(payMode);
                if (index > -1) {
                    selected.splice(index, 1);
                    $scope.payModeTable[payMode].show = false;
                } else {
                    selected.push(payMode);
                    $scope.payModeTable[payMode].show = true;
                }
            };
            $scope.someSelected = function (object) {
                return Object.keys(object).some(function (key) {
                    return object[key];
                });
            };
            $scope.acquirerChange = function (object, value, second) {
                var account = [];
                angular.forEach(init.acquirerAccount, function (val) {
                    if (val.acquirerId === value) {
                        account.push(val);
                    }
                });
                if (second) {
                    object.secondAcquirerAccount = account;
                } else {
                    object.acquirerAccount = account;
                }
            };
            // 初始化显示信息并获取商户汇率
            httpSvc.getData('post', '/merchant/getMerchantPayInit').then(function (value) {
                init = value;
                $scope.currency = value.currency;
                $scope.encrypt = value.encrypt;
                $scope.status = value.status;
                $scope.payMode = value.payMode;
                $scope.interfaceType = value.interfaceType;
                $scope.acquirer = value.acquirer;
                // 初始化payModeTable
                angular.forEach($scope.payMode, function (value1) {
                    // 初始化选择收单账户对象
                    for (var i = 0; i < init[value1.firstValue].length; i++) {
                        init[value1.firstValue][i].acquirerAccount = [];
                        init[value1.firstValue][i].secondAcquirerAccount = [];
                    }
                    // 将支付方式放入payModeTable内
                    $scope.payModeTable[value1.firstValue] = value1;
                    // 判断商户支持支付方式，若支持显示
                    $scope.payModeTable[value1.firstValue].show = $scope.merchantPay.payMode.indexOf(value1.firstValue) > -1;
                    // 初始化支付类型
                    $scope.payModeTable[value1.firstValue].payType = init[value1.firstValue];
                });
                // 获取商户汇率
                httpSvc.getData('post', '/merchant/getMerchantRateByRefIdAndRefType', {
                    refId: $stateParams.webSiteInfo.id,
                    refType: 2
                }).then(function (value1) {
                    if (value1.length > 0) {
                        organizeRateData(value1);
                    }
                });
            });
            $scope.confirmDisabled = function (myForm) {
                return !myForm.$valid;
            };
            $scope.confirm = function () {
                organizeData();
                httpSvc.getData('post', '/merchant/updateMerchantPay', $scope.merchantPay).then(function (value) {
                    if (value) {
                        if ($scope.merchantPay.merchantRateList.length > 0) {
                            httpSvc.getData('post', '/merchant/updateMerchantRateByList', $scope.merchantPay.merchantRateList).then(function (value1) {
                                if (value1) {
                                    toaster.pop({
                                        type: 'success',
                                        title: '域名管理',
                                        body: '更新商户域名扣率成功！'
                                    });
                                    $state.go('base_view.business.merchant_web_site');
                                } else {
                                    toaster.pop({
                                        type: 'error',
                                        title: '域名管理',
                                        body: '更新商户域名扣率失败！'
                                    });
                                }
                            });
                        } else {
                            toaster.pop({
                                type: 'success',
                                title: '域名管理',
                                body: '更新商户域名扣率成功！'
                            });
                            $state.go('base_view.business.merchant_web_site');
                        }
                    } else {
                        toaster.pop({
                            type: 'error',
                            title: '商户管理',
                            body: '更新商户域名扣率失败！'
                        });
                    }
                });
            };
            $scope.cancel = function () {
                $state.go('base_view.business.merchant_web_site');
            }
        });
    } else {
        $state.go('base_view.business.merchant_web_site');
    }

    function organizeData() {
        angular.forEach($scope.merchantPay.payMode, function (value) {
            for (var i = 0; i < $scope.payModeTable[value].payType.length; i++) {
                if ($scope.payModeTable[value].payType[i].rate !== undefined) {
                    $scope.payModeTable[value].payType[i].refId = $stateParams.webSiteInfo.id;
                    // refType：1商户扣率，；2，商户网址扣率
                    $scope.payModeTable[value].payType[i].refType = 2;
                    $scope.payModeTable[value].payType[i].payMode = value;
                    $scope.payModeTable[value].payType[i].payType = $scope.payModeTable[value].payType[i].firstValue;
                    $scope.payModeTable[value].payType[i].bailCycle = $scope.merchantPay.bailCycle;
                    $scope.payModeTable[value].payType[i].bailRate = $scope.merchantPay.bailRate;
                    $scope.merchantPay.merchantRateList.push($scope.payModeTable[value].payType[i]);
                }
            }
        });
        $scope.merchantPay.currency = $scope.merchantPay.currency.toString();
        $scope.merchantPay.payMode = $scope.merchantPay.payMode.toString();
    }

    function organizeRateData(value) {
        $scope.merchantPay.bailCycle = value[0].bailCycle;
        $scope.merchantPay.bailRate = value[0].bailRate;
        // 将商户汇率对象放入payModeTable显示
        angular.forEach($scope.payModeTable, function (obj, key) {
            for (var i = 0; i < value.length; i++) {
                if (value[i].payMode === key) {
                    for (var j = 0; j < obj.payType.length; j++) {
                        if (obj.payType[j].firstValue === value[i].payType) {
                            angular.extend(obj.payType[j], value[i]);
                            $scope.acquirerChange(obj.payType[j], obj.payType[j].acquirerId, false);
                            $scope.acquirerChange(obj.payType[j], obj.payType[j].secondAcquirerId, true);
                            break;
                        }
                    }
                }
            }
        });
    }
}

// 产品管理（产品类型）
function merchantWebsiteProTypeCtrl($scope, $uibModal, NgTableParams, httpSvc, toaster) {
    var websiteProType;
    $scope.selected = {};
    $scope.showModal = $scope.edit = function (type, websiteProType) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/business/merchant_website_pro_type_modal',
            controller: 'merchantWebsiteProTypeModalCtrl',
            resolve: {
                type: function () {
                    return type;
                },
                websiteProType: function () {
                    return websiteProType;
                }
            }
        });
        modalInstance.result.then(function () {
            tableReload();
        }, function () {

        });
    };
    httpSvc.getData('post', '/merchant/webSite/getAllProType').then(function (value) {
        websiteProType = value;
        $scope.merchantWebsiteProTypeTable = new NgTableParams({}, {
            dataset: value
        });
        angular.element('.ibox-content').removeClass('sk-loading');
    });
    $scope.del = function () {
        var idList = [];
        for (var id in $scope.selected) {
            if ($scope.selected[id]) {
                idList.push(id);
            }
        }
        httpSvc.getData('post', '/merchant/webSite/deleteProType', idList).then(function (value) {
            if (value.length === 0) {
                toaster.pop({
                    type: 'success',
                    title: '产品管理',
                    body: '删除产品类型成功！'
                });
            } else {
                var toasterBody = '';
                for (var i = 0; i < value.length; i++) {
                    for (var j = 0; j < websiteProType.length; j++) {
                        if (value[i] === websiteProType[j].id) {
                            toasterBody += websiteProType[j].productTypeName;
                            toasterBody += '；';
                            break;
                        }
                    }
                }
                toaster.pop({
                    type: 'warning',
                    title: '产品管理',
                    body: '产品类型 ' + toasterBody + ' 存在订单，无法删除！',
                    timeout: 0
                });
            }
            $scope.selected = {};
            tableReload();
        });
    };
    $scope.delDisabled = function () {
        for (var id in $scope.selected) {
            if ($scope.selected[id]) {
                return false;
            }
        }
        return true;
    };

    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/merchant/webSite/getAllProType').then(function (value) {
            websiteProType = value;
            $scope.merchantWebsiteProTypeTable.settings({
                dataset: value
            });
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }
}

// 产品管理（产品类型）弹窗
function merchantWebsiteProTypeModalCtrl($scope, $uibModalInstance, httpSvc, type, websiteProType, toaster) {
    $scope.type = type;
    $scope.cancel = function () {
        $uibModalInstance.dismiss()
    };
    if (type === 1) {
        $scope.websiteProType = websiteProType;
        $scope.websiteProType.productTypeId = Number(websiteProType.productTypeId);
    }
    $scope.productTypeNameBlur = $scope.productTypeIdBlur = function ($event, value) {
        verification(value, $event.target);
    };
    $scope.confirm = function (websiteProType) {
        if (type === 0) {
            httpSvc.getData('post', '/merchant/webSite/addProType', websiteProType).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '产品管理',
                        body: '添加产品类型成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '产品管理',
                        body: '添加产品类型失败！'
                    });
                }
            });
        } else {
            httpSvc.getData('post', '/merchant/webSite/updateProType', websiteProType).then(function (value) {
                if (value) {
                    toaster.pop({
                        type: 'success',
                        title: '产品管理',
                        body: '更新产品类型成功！'
                    });
                    $uibModalInstance.close();
                } else {
                    toaster.pop({
                        type: 'error',
                        title: '产品管理',
                        body: '更新产品类型失败！'
                    });
                }
            });
        }
    };
}

// 快捷测试
function quickTestCtrl($scope, $uibModal, NgTableParams, httpSvc, toaster, $filter) {
    var init;
    var billNo = $filter('date')(new Date(), 'yyyyMMddHHmmsss');
    // 获取初始化参数
    httpSvc.getData('post', '/merchant/quickTest/getInit').then(function (value) {
        init = value;
        $scope.merchantInfo = value.merchantInfo;
        $scope.currency = value.currency;
        $scope.lang = value.lang;
        $scope.payMode = value.payMode;
        $scope.country = value.country;
        // 初始化参数
        $scope.quickTest = {
            merNo: '1115',
            billNo: billNo,
            amount: 10,
            freight: 5,
            fee: 1,
            currency: 'USD',
            customerId: 12580,
            billFirstName: 'wang',
            billLastName: 'hong',
            billAddress: 'Qixing west road',
            billCity: 'Xiamen',
            billState: 'Fujian',
            billCountry: 'CN',
            billZip: '361000',
            billEmail: '10000@qq.com',
            billPhone: '114118',
            shipFirstName: 'wang',
            shipLastName: 'hong',
            shipAddress: 'Qixing west road',
            shipCity: 'Xiamen',
            shipState: 'Fujian',
            shipCountry: 'CN',
            shipZip: '361000',
            shipEmail: '10000@qq.com',
            shipPhone: '114118',
            lang: 'en',
            payMode: 'Credit',
            payType: 'Visa',
            returnURL: '/',
            notifyURL: '/',
            remark: '快捷测试',
            ip: '127.0.0.1',
            cardNo: 4111111111111111,
            issue: 'China Bank',
            securityNum: 9912,
            expireYear: 2099,
            expireMonth: 12,
            productDetails: [{goodId: 10086, goodName: 'tea', price: 5, qty: 2}]
        };
        $scope.$watch('quickTest.merNo', function (newVal) {
            if (newVal !== undefined) {
                newVal = Number(newVal);
                for (var i = 0; i < init.merchantPay.length; i++) {
                    if (newVal === init.merchantPay[i].refId) {
                        $scope.quickTest.md5Info = init.merchantPay[i].secretKey;
                        break;
                    }
                }
            }
        });
        $scope.$watch('quickTest.payMode', function (newVal) {
            if (newVal !== undefined) {
                $scope.payType = init[newVal];
            }
        });
        $scope.$watch('quickTest.merNo', function (newVal) {
            if (newVal !== undefined) {
                for (var i = 0; i < init.merchantPay.length; i++) {
                    if (newVal === init.merchantPay[i].refId) {
                        $scope.quickTest.md5Info = init.merchantPay[i].secretKey;
                        break;
                    }
                }
            }
        });
        $scope.$watch('quickTest.payMode', function (newVal) {
            if (newVal !== undefined) {
                $scope.payType = init[newVal];
            }
        });
        $scope.$watch('activeForm', function (newVal) {
            $scope.quickTest.payURL = null;
            switch (newVal) {
                case 0:
                    $scope.quickTestURL = init.inlinePayURL;
                    $scope.quickTest.transType = 0;
                    break;
                case 1:
                    $scope.quickTestURL = init.crossPayURL;
                    $scope.quickTest.transType = 1;
                    break;
                default:
                    break;
            }
        });
        angular.element('.ibox-content').removeClass('sk-loading');
    });
}

// 确认弹窗
function alertModalCtrl($scope, $uibModalInstance, title, content) {
    $scope.alertTitle = title;
    $scope.alertContent = content;
    $scope.confirm = function () {
        $uibModalInstance.close();
    };
    $scope.cancel = function () {
        $uibModalInstance.dismiss();
    };
}

/**
 * 系统常量配置管理
 *
 */

function constantInfoCtrl($scope, $uibModal, NgTableParams, httpSvc, toaster) {

    $scope.groupList = [{id: '', title: '--请选择常量组别--'}];
    $scope.constantTable = new NgTableParams({}, {
        getData: function (params) {
            angular.element('.ibox-content').addClass('sk-loading');
            return httpSvc.getData('post', '/constant/getConstantInfo', {

                pageFirst: params.page() - 1,
                pageSize: params.count(),
                sortFieldName: "id",
                sortType: "desc",
                searchInfo: params.filter()

            }).then(function (value) {

                $scope.totalItems = value.resultTotal;
                params.total(value.resultTotal);
                angular.element('.ibox-content').removeClass('sk-loading');

                return value.constantList;

            });
        }
    });

    httpSvc.getData('post', '/constant/getGroupAll').then(function (value) {
        for (var i = 0; i < value.length; i++) {
            $scope.groupList.push({
                id: value[i].code,
                title: value[i].name

            });
        }
    });

    function tableReload() {
        angular.element('.ibox-content').addClass('sk-loading');
        httpSvc.getData('post', '/constant/getConstantList', {}).then(function (value) {
            $scope.constantTable.settings({
                dataset: value
            });
            $scope.totalItems = value.length;
            angular.element('.ibox-content').removeClass('sk-loading');
        });
    }

    $scope.showModal = function (constant) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/constant/constantUpdate',
            controller: 'constantInfoEditModalCtrl',
            resolve: {
                constant: function () {
                    return constant;
                }
            }
        });
        modalInstance.result.then(function () {
            tableReload()
        }, function () {
            tableReload()
        });
    };


    $scope.showAddModal = function (constant) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/constant/constantAdd',
            controller: 'constantInfoAddModalCtrl',
            resolve: {
                constant: constant
            }
        });
        modalInstance.result.then(function () {
            tableReload()
        }, function () {
            tableReload()
        });
    };

    var idArr = [];
    $scope.delDisabled = true;
    $scope.collectSelectRows = function ($event, id) {

        var isChecked = angular.element($event.target).prop("checked");

        if (isChecked == true) {

            idArr.push(id);
            $scope.delDisabled = false;

        } else {

            idArr.remove(id);

        }

        if (idArr.length == 0) {

            $scope.delDisabled = true;

        }

    }

    // 批量删除
    $scope.batchDel = function () {

        var ids = idArr.join(",");
        httpSvc.getData('post', '/constant/batchDel', {ids: ids}).then(function (value) {

            if (value.result == 1) {

                toaster.pop({
                    type: 'success',
                    title: '系统常量删除',
                    body: '删除成功！'
                });

            } else {

                toaster.pop({
                    type: 'error',
                    title: '系统常量删除',
                    body: '删除失败！'
                });

            }

            idArr = [];

            tableReload();


        });


        $scope.delDisabled = true;


    }


}

// 添加系统常量配置
function constantInfoAddModalCtrl($scope, $uibModalInstance, httpSvc, toaster, constant) {

    $scope.constant = constant;
    httpSvc.getData('post', '/constant/getGroupAll').then(function (value) {

        $scope.groupList = value;

    });

    $scope.back = function () {

        $uibModalInstance.dismiss();

    };


    $scope.optionMouseOver = function ($event) {


        angular.element($event.target).parent().val("String");


    }

    $scope.optionMouseClick = function ($event) {

        angular.element($event.target).parent().attr("size", 0);
        var id = angular.element($event.target).parent().attr("id");
        angular.element("#selectInputDiv_" + id).remove();


    }

    $scope.addSortValueDisabled = true;

    $scope.nameFocus = function () {

        angular.element("#name").addClass("has-success");
        angular.element("#name").removeClass("has-error");
        angular.element("input:not(#name)").removeClass("has-success");

    }

    $scope.nameBlur = function () {

        var name = angular.element("#name").val();
        if (null == name || name == "") {

            angular.element("#name").addClass("has-error");
            angular.element("#name").removeClass("has-success");

        }

    }

    $scope.firstValueFocus = function () {

        angular.element("#firstValue").removeClass("has-error");
        angular.element("#firstValue").addClass("has-success");
        angular.element("input:not(#firstValue)").removeClass("has-success");
        angular.element("select:not(#firstValue)").removeClass("has-success");

    }

    $scope.firstValueBlur = function () {
        var firstValue = angular.element("#firstValue").val();
        if (null == firstValue || firstValue == "") {

            angular.element("#firstValue").addClass("has-error");
            angular.element("#firstValue").removeClass("has-success");

        }

    }


    $scope.sortValueFocus = function () {

        angular.element("#sortValue").removeClass("has-error");
        angular.element("#sortValue").addClass("has-success");
        angular.element("input:not(#sortValue)").removeClass("has-success");
        angular.element("select:not(#sortValue)").removeClass("has-success");
        $scope.addSortValueDisabled = false;

    }

    $scope.sortValueBlur = function () {
        var sortValue = angular.element("#sortValue").val();
        if (null != sortValue && sortValue != "" && !/^\d+?$/.test(sortValue)) {

            $scope.addSortValueDisabled = true;
            angular.element("#sortValue").addClass("has-error");
            angular.element("#sortValue").removeClass("has-success");

        }

    }

    $scope.groupCodeChange = function () {

        var groupCode = angular.element("#groupCode").val();
        angular.element("#groupCode").attr("size", "0");
        if (null == groupCode || groupCode == "") {

            angular.element("#groupCode").addClass("has-error");
            angular.element("#groupCode").removeClass("has-success");

            angular.element("#groupCodePrompt").addClass("select-prompt");
            angular.element("#groupCodePrompt").removeClass("no-select-prompt");


        } else {

            angular.element("#groupCode").removeClass("has-error");
            angular.element("#groupCode").addClass("has-success");

            angular.element("#groupCodePrompt").removeClass("select-prompt");
            angular.element("#groupCodePrompt").addClass("no-select-prompt");

        }


        angular.element("input:not(#groupCode)").removeClass("has-success");
        $("#selectInputDiv_groupCode").remove();

    }

    var idSave = "";
    $scope.groupCodeMouseDown = function ($event) {

        var id = angular.element($event.target).attr("id");
        var size = angular.element($event.target).attr("size");
        if (size == undefined) {

            size = 7;

        }
        if (id !== undefined) {

            idSave = id;
            angular.element($event.target).attr("size", "7");


        } else {

            angular.element($event.target).attr("size", "0");

        }

        if (id == undefined || size == 7) {

            len = 1;

        } else {

            len = 0

        }

        if (len == 0) {

            var addHtml = '<div id="selectInputDiv_' + idSave + '" class="align-middle" ><img src="img/arrow/arrow.png" class="select-arrow" /><input type="text" id="selectInput" name="selectInput" class="form-control limit-height" /></div>';
            angular.element($event.target).before(addHtml);

        }

        angular.element("input:not(#groupCode)").removeClass("has-success");
        angular.element("#groupCodePrompt").removeClass("select-prompt");
        angular.element("#groupCodePrompt").addClass("no-select-prompt");

    }


    $scope.groupCodeBlur = function () {

        var id = angular.element("#groupCode").attr("id");
        var groupCode = angular.element("#groupCode").val();
        angular.element("#groupCode").attr("size", "0");
        var len = angular.element("#selectInputDiv_" + id).length;
        if (len > 0) {

            angular.element("#selectInputDiv_" + id).remove();

        }
        if (null == groupCode || groupCode == "") {

            angular.element("#groupCode").addClass("has-error");
            angular.element("#groupCode").removeClass("has-success");
            $scope.addIsDisabled = true;
            angular.element("#groupCodePrompt").addClass("select-prompt");
            angular.element("#groupCodePrompt").removeClass("no-select-prompt");

        } else {

            angular.element("#groupCode").removeClass("has-error");
            angular.element("#groupCode").addClass("has-success");
            $scope.addIsDisabled = false;
            angular.element("#groupCodePrompt").removeClass("select-prompt");
            angular.element("#groupCodePrompt").addClass("no-select-prompt");

        }

    }

    $scope.generalFocus = function ($event) {

        $scope.addIsDisabled = false;
        var id = angular.element($event.target).attr("id");
        angular.element("input:not(#" + id + ")").removeClass("has-success");
        angular.element("select:not(#" + id + ")").removeClass("has-success");

    }

    $scope.addConstant = function () {

        var obj = angular.element("#constantObjForm").serializeJson();

        httpSvc.getData('post', '/constant/save', obj).then(function (value) {

            if (value.success == 1) {

                toaster.pop({
                    type: 'success',
                    title: '系统常量添加',
                    body: '添加成功！'
                });

            } else {

                toaster.pop({
                    type: 'error',
                    title: '系统常量添加',
                    body: '添加失败！'
                });

            }

            $uibModalInstance.dismiss();

        });

        $scope.addIsDisabled = true;

    }


}

// 编辑系统常量配置
function constantInfoEditModalCtrl($scope, $uibModalInstance, httpSvc, toaster, constant) {

    $scope.updateIsDisabled = true;
    $scope.updateSortValueDisabled = false;

    $scope.constant = constant;
    httpSvc.getData('post', '/constant/getGroupAll').then(function (value) {

        $scope.groupList = value;

    });

    $scope.back = function () {

        $uibModalInstance.dismiss();

    };

    $scope.optionMouseOver = function ($event) {


        angular.element($event.target).parent().val("String");


    }

    $scope.optionMouseClick = function ($event) {

        angular.element($event.target).parent().attr("size", 0);
        var id = angular.element($event.target).parent().attr("id");
        angular.element("#selectInputDiv_" + id).remove();


    }

    $scope.nameFocus = function () {

        $scope.updateIsDisabled = false;
        angular.element("#name").addClass("has-success");
        angular.element("#name").removeClass("has-error");
        angular.element("input:not(#name)").removeClass("has-success");
        angular.element("select:not(#name)").removeClass("has-success");

    }

    $scope.nameBlur = function () {

        var name = angular.element("#name").val();
        if (null == name || name == "") {

            $scope.updateIsDisabled = true;
            angular.element("#name").addClass("has-error");
            angular.element("#name").removeClass("has-success");

        }

    }

    $scope.sortValueFocus = function () {

        angular.element("#sortValue").removeClass("has-error");
        angular.element("#sortValue").addClass("has-success");
        angular.element("input:not(#sortValue)").removeClass("has-success");
        angular.element("select:not(#sortValue)").removeClass("has-success");
        $scope.updateSortValueDisabled = false;

    }

    $scope.sortValueBlur = function () {
        var sortValue = angular.element("#sortValue").val();
        if (null != sortValue && sortValue != "" && !/^\d+?$/.test(sortValue)) {

            $scope.updateSortValueDisabled = true;
            angular.element("#sortValue").addClass("has-error");
            angular.element("#sortValue").removeClass("has-success");

        }

    }

    var idSave = "";
    $scope.groupCodeMouseDown = function ($event) {

        var id = angular.element($event.target).attr("id");
        var size = angular.element($event.target).attr("size");
        if (size == undefined) {

            size = 7;

        }
        if (id !== undefined) {

            idSave = id;
            angular.element($event.target).attr("size", "7");


        } else {

            angular.element($event.target).attr("size", "0");

        }

        if (id == undefined || size == 7) {

            len = 1;

        } else {

            len = 0

        }

        if (len == 0) {

            var addHtml = '<div id="selectInputDiv_' + idSave + '" class="align-middle" ><img src="img/arrow/arrow.png" class="select-arrow" /><input type="text" id="selectInput" name="selectInput" class="form-control limit-height" /></div>';
            angular.element($event.target).before(addHtml);

        }

        angular.element("input:not(#groupCode)").removeClass("has-success");
        angular.element("#groupCodePrompt").removeClass("select-prompt");
        angular.element("#groupCodePrompt").addClass("no-select-prompt");

    }

    $scope.firstValueFocus = function () {

        $scope.updateIsDisabled = false;
        angular.element("#firstValue").removeClass("has-error");
        angular.element("#firstValue").addClass("has-success");
        angular.element("input:not(#firstValue)").removeClass("has-success");

    }

    $scope.firstValueBlur = function () {

        var firstValue = angular.element("#firstValue").val();
        if (null == firstValue || firstValue == "") {

            $scope.updateIsDisabled = true;
            angular.element("#firstValue").addClass("has-error");
            angular.element("#firstValue").removeClass("has-success");

        }

    }

    $scope.groupCodeChange = function () {

        var groupCode = angular.element("#groupCode").val();
        angular.element("#groupCode").attr("size", "0");
        if (null == groupCode || groupCode == "") {

            angular.element("#groupCode").addClass("has-error");
            angular.element("#groupCode").removeClass("has-success");

            angular.element("#groupCodePrompt").addClass("select-prompt");
            angular.element("#groupCodePrompt").removeClass("no-select-prompt");

            $scope.updateIsDisabled = true;

        } else {

            angular.element("#groupCode").removeClass("has-error");
            angular.element("#groupCode").addClass("has-success");

            angular.element("#groupCodePrompt").removeClass("select-prompt");
            angular.element("#groupCodePrompt").addClass("no-select-prompt");

            $scope.updateIsDisabled = false;


        }

        angular.element("input:not(#groupCode)").removeClass("has-success");
        $("#selectInputDiv_groupCode").remove();

    }


    $scope.groupCodeBlur = function () {

        var groupCode = angular.element("#groupCode").val();
        angular.element("#groupCode").attr("size", "0");
        var id = angular.element("#groupCode").attr("id");
        var len = angular.element("#selectInputDiv_" + id).length;
        if (len > 0) {

            angular.element("#selectInputDiv_" + id).remove();

        }
        if (null == groupCode || groupCode == "") {

            angular.element("#groupCode").addClass("has-error");
            angular.element("#groupCode").removeClass("has-success");
            $scope.addIsDisabled = true;
            angular.element("#groupCodePrompt").addClass("select-prompt");
            angular.element("#groupCodePrompt").removeClass("no-select-prompt");

        } else {

            angular.element("#groupCode").removeClass("has-error");
            angular.element("#groupCode").addClass("has-success");
            $scope.updateIsDisabled = false;
            angular.element("#groupCodePrompt").removeClass("select-prompt");
            angular.element("#groupCodePrompt").addClass("no-select-prompt");

        }


    }

    $scope.generalFocus = function ($event) {

        $scope.updateIsDisabled = false;
        var id = angular.element($event.target).attr("id");
        angular.element("input:not(#" + id + ")").removeClass("has-success");
        angular.element("select:not(#" + id + ")").removeClass("has-success");

    }

    $scope.updateConstant = function () {

        var obj = angular.element("#constantObjForm").serializeJson();

        httpSvc.getData('post', '/constant/update', obj).then(function (value) {

            if (value.success == 1) {

                toaster.pop({
                    type: 'success',
                    title: '系统常量编辑',
                    body: '更新成功！'
                });

            } else {

                toaster.pop({
                    type: 'error',
                    title: '系统常量编辑',
                    body: '更新失败！'
                });


            }

            $uibModalInstance.dismiss();

        });

        $scope.updateIsDisabled = true;

    }


}


/**
 * 商户余额
 *
 */

function businessMoneyInfoCtrl($scope, $state, $http, $timeout, httpSvc) {

    $scope.merTips = false;

    httpSvc.getData('post', '/businessMoney/getMerIdsInit').then(function (value) {
        $scope.merchants = value.merchants;
    });


    $scope.$watch('selectedMerchant', function (newVal) {

        if (newVal !== undefined) {

            var merId = newVal.title;

            if (merId != "") {

                angular.element(".promptError").hide();
                angular.element('input[name="merId"]').removeClass("has-error");

                $timeout(function () {
                    $http({
                        method: 'post',
                        url: '/businessMoney/getDetails',
                        data: merId
                    }).then(function (response) {

                        if (angular.equals(0, response.data.bondReleaseAmount)) {

                            $scope.bondReleaseAmount = response.data.bondReleaseAmount;

                        } else {

                            $scope.bondReleaseAmount = -response.data.bondReleaseAmount;

                        }

                        if (angular.equals(0, response.data.protestPlusAmount)) {

                            $scope.protestPlusAmount = response.data.protestPlusAmount;

                        } else {

                            $scope.protestPlusAmount = -response.data.protestPlusAmount;

                        }

                        if (angular.equals(0, response.data.feePlusAmount)) {

                            $scope.feePlusAmount = response.data.feePlusAmount;

                        } else {

                            $scope.feePlusAmount = -response.data.feePlusAmount;

                        }

                        if (angular.equals(0, response.data.drawingNoAuditPlusAmount)) {

                            $scope.drawingNoAuditPlusAmount = response.data.drawingNoAuditPlusAmount;

                        } else {

                            $scope.drawingNoAuditPlusAmount = -response.data.drawingNoAuditPlusAmount;

                        }

                        if (angular.equals(0, response.data.drawingAuditPlusAmount)) {

                            $scope.drawingAuditPlusAmount = response.data.drawingAuditPlusAmount;

                        } else {

                            $scope.drawingAuditPlusAmount = -response.data.drawingAuditPlusAmount;

                        }

                        if (angular.equals(0, response.data.refundPlusAmount)) {

                            $scope.refundPlusAmount = response.data.refundPlusAmount;

                        } else {

                            $scope.refundPlusAmount = -response.data.refundPlusAmount;

                        }

                        if (angular.equals(0, response.data.deductPlusAmount)) {

                            $scope.deductPlusAmount = response.data.deductPlusAmount;

                        } else {

                            $scope.deductPlusAmount = -response.data.deductPlusAmount;

                        }

                        if (angular.equals(0, response.data.settlePlusAmount)) {

                            $scope.settlePlusAmount = response.data.settlePlusAmount;

                        } else {

                            $scope.settlePlusAmount = -response.data.settlePlusAmount;

                        }

                        $scope.returnDeductAmount = response.data.returnDeductAmount;
                        $scope.bondNoReleaseAmount = response.data.bondNoReleaseAmount;
                        $scope.preDisabledAmount = response.data.preDisabledAmount;
                        $scope.finalNoSettleAmount = response.data.finalNoSettleAmount;
                        $scope.finalUsableAmount = response.data.finalUsableAmount;
                        $scope.preBondAmount = response.data.preBondAmount;
                        $scope.preUsableAmount = response.data.preUsableAmount;
                        $scope.finalBondAmount = response.data.finalBondAmount;
                        $scope.nosettlePlusAmount = response.data.nosettlePlusAmount;


                    });

                })

            } else {

                angular.element(".promptError").show();
                angular.element('input[name="merId"]').addClass("has-error");

            }

            $scope.merTips = false;


        }

    });


    $scope.resetForm = function () {

        $scope.$broadcast('angucomplete-alt:clearInput');
        angular.element("#businessMoneyTB").hide();
        angular.element("#promptNoneID").hide();
        angular.element("#businessMoneyDetailsID").addClass("displayStatus");

    }

}


/**
 * 商户日对账和月对账单
 *
 */

function businessReconMoneyInfoCtrl($scope, $state, $http, $timeout, httpSvc) {

    $scope.merTips = false;

    $scope.dailyOrMonth = 1;

    getReconDateList(null, 1);

    angular.element(".ibox-title ul li").each(function () {

        angular.element(this).click(function () {

            angular.element(this).siblings().removeClass("current");
            angular.element(this).addClass("current");

            angular.element("#promptNoneID").css("display", "none");

            var txt = $(this).text();

            if (txt == "日交易对账单") {

                angular.element("#dailyOrMonth").val("1");
                $scope.dailyOrMonth = 1;
                getReconDateList(null, 1);
                $scope.$broadcast('angucomplete-alt:clearInput');


            } else {

                angular.element("#dailyOrMonth").val("2");
                $scope.dailyOrMonth = 2;
                getReconDateList(null, 2);
                $scope.$broadcast('angucomplete-alt:clearInput');

            }

            angular.element(".promptError").hide();
            angular.element('input[name="merId"]').removeClass("has-error");

            angular.element("#businessReconTBID").empty();

        });


    });


    Date.prototype.Format = function (fmt) {
        var o = {
            "M+": this.getMonth() + 1,                 // 月份
            "d+": this.getDate(),                    // 日
            "h+": this.getHours(),                   // 小时
            "m+": this.getMinutes(),                 // 分
            "s+": this.getSeconds(),                 // 秒
            "q+": Math.floor((this.getMonth() + 3) / 3), // 季度
            "S": this.getMilliseconds()             // 毫秒
        };

        if (/(y+)/.test(fmt))
            fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length)); // 格式化年份
        for (var k in o) // 循环获取上面定义的月、日、小时等，格式化对应的数据。
            if (new RegExp("(" + k + ")").test(fmt))
                fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
        return fmt;
    }


    // 初始化对账时间列表
    function getReconDateList(merId, reconType) {

        var data = {};
        data = {merId: merId, reconType: reconType};
        httpSvc.getData('post', '/businessRecon/getReconDateList', data
        ).then(function (value) {

            var data = value.businessReconMoneyList;
            angular.element("#reconDate").find("option:gt(0)").remove();
            for (var i = 0; i < data.length; i++) {
                var optionHtml = "";
                if (reconType == 1) {

                    optionHtml = '<option value="' + data[i].reconDate + '">' + new Date(data[i].reconDate).Format("yyyy年MM月") + '</option>';

                } else {

                    optionHtml = '<option value="' + data[i].reconDate + '">' + new Date(data[i].reconDate).Format("yyyy年") + '</option>';

                }

                angular.element("#reconDate").append(optionHtml);


            }

        });


    }

    $scope.$watch('dailyOrMonth', function(newValue,oldValue){

        httpSvc.getData('post', '/businessRecon/getRecentTradeMerIds',{reconType:angular.element("#dailyOrMonth").val()}).then(function (value) {

            $scope.merchants = value.businessReconMoneyList;


        })

    });

    $scope.$watch('selectedMerchant', function (newVal) {
        if (newVal !== undefined) {

            var merId = newVal.title;
            if(merId != ""){
                angular.element(".promptError").hide();
                angular.element('input[name="merId"]').removeClass("has-error");

            }else{

                angular.element(".promptError").show();
                angular.element('input[name="merId"]').addClass("has-error");

            }

            $scope.merTips = false;

        }

    });

    $scope.resetForm = function(){

        $scope.$broadcast('angucomplete-alt:clearInput');
        angular.element("#reconDate").val("");
        angular.element("#businessReconTBID").empty();

    }

}

/**
 * 退款拒付列表获取
 *
 */

function orderChangeInfoCtrl($scope, $timeout, $uibModal, $document, $filter, toaster, NgTableParams, httpSvc, csvExp) {

    $scope.merTips = false;
    $scope.minText = 3;
    $scope.orderTypeTxt = '平台订单号';
    $scope.orderType = 'orderId';
    $scope.init = null;
    var merWeb = [];
    var searchInfo = null;
    $scope.refId;



    httpSvc.getData('post', '/orderChange/getOrderChangeInit').then(function (value) {
        $scope.merchants = value.merchants;
        $scope.siteUrls = value.siteUrls;
        $scope.exceptionStatusList = value.exceptionStatusList;
        $scope.acquirerAccounts = value.acquirerAccounts;
        $scope.init = value;
    });

    $scope.orderChangeTable = new NgTableParams({}, {
        getData: function (params) {
            angular.element('.ibox-content').addClass('sk-loading');
            return httpSvc.getData('post', '/orderChange/getOrderChangeInfo', {
                pageFirst: (params.page()-1)*10,
                pageSize: params.count(),
                sortFieldName:"audit_time",
                sortType:"desc",
                exceptionType:angular.element("#exceptionType").val(),
                status:1,
                searchInfo:searchInfo
            }).then(function (value) {

                $scope.totalItems = value.resultTotal;
                params.total(value.resultTotal);
                $scope.orderChangeStatistics = value.orderChangeStatistics;
                angular.element('.ibox-content').removeClass('sk-loading');
                return value.orderChangeList;

            });
        }
    });

    $scope.orderChangeTable.enableColumnResizing = true;

    $timeout(function () {

        $scope.$watch('selectedMerchant', function (newVal) {
            if (newVal !== undefined) {
                merWeb = [];
                var input = newVal.title;
                for (var i = 0, j = $scope.init.siteUrls.length; i < j; i++) {
                    if ($scope.init.siteUrls[i].merId == input) {
                        merWeb.push($scope.init.siteUrls[i]);
                    }
                }
                $scope.siteUrls = merWeb;
                $scope.minText = 0;
                $scope.merTips = false;
            } else {
                $scope.minText = 3;
                if ($scope.siteUrls !== undefined) {
                    $scope.siteUrls = $scope.init.siteUrls;
                }
                merWeb = [];
            }

            $scope.$broadcast('angucomplete-alt:clearInput', 'mer_web');

        });

        $scope.$watch('myform.merId.$modelValue', function (newVal) {
            if (newVal !== '' && newVal !== undefined && $scope.selectedMerchant === undefined) {
                $scope.merTips = true;
            } else {
                $scope.merTips = false;
            }
        });

        $scope.$watch('auditBeginDate', function (newVal) {
            if (newVal !== '' && newVal !== undefined && newVal != null) {
                $scope.dateOptions2.minDate = $scope.auditBeginDate;
                $scope.auditEndDateDisable = false;
                if (oldEndDate !== '') {
                    $scope.auditBeginDate = oldEndDate;
                }
            } else {
                $scope.auditEndDateDisable = true;
                oldEndDate = $scope.auditBeginDate;
                $scope.auditBeginDate = '';
            }
        });


    });

    $scope.orderSwitch = function ($event, orderType) {


        $scope.orderTypeTxt = angular.element($event.target).text();
        $scope.orderType = orderType;
    };


    // Datepicker
    var oldEndDate = '';
    $scope.auditEndDateDisable = true;

    $scope.format = 'yyyy/MM/dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };

    $scope.searchOrder = function (data) {
        if (data != null) {
            if (data.siteId !== undefined && data.siteId != null) {
                for (var i = 0, j = $scope.init.siteUrls.length; i < j; i++) {
                    if ($scope.init.siteUrls[i].siteUrl === data.siteId) {
                        data.siteId = $scope.init.siteUrls[i].id;
                        break;
                    }
                }
            }
        }
        searchInfo = data;
        $scope.orderChangeTable.reload();
        $scope.orderChangeTable.page(1);
    };

    $scope.resetForm = function () {
        angular.element('#orderId').val('');
        angular.element('#merOrderId').val('');
        angular.element('#bankOrderId').val('');
        angular.element('#merId').val('');
        angular.element('#siteId').val('');
        angular.element('#accountId').val('');
        angular.element('#applicant').val('');
        angular.element('#auditor').val('');
        angular.element('#type').val('');
        angular.element('#auditBeginDate').val('');
        angular.element('#auditEndDate').val('');
        $scope.dateOptions1 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.dateOptions2 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        searchInfo = null;
        $scope.auditEndDateDisable = true;
        $scope.orderType = 'orderId';
        $scope.orderTypeTxt = '平台订单号';
        $scope.$broadcast('angucomplete-alt:clearInput');
        $scope.orderChangeTable.reload();
        $scope.orderChangeTable.page(1);
    };

    // 导出
    $scope.exportCsv = function () {

        httpSvc.getData('post', '/orderChange/getOrderChangeInfo',

            {
                exceptionType:angular.element("#exceptionType").val(),
                status:1,
                searchInfo:searchInfo

            }


        ).then(function (value) {
            var exceptionType = angular.element("#exceptionType").val();
            var title = [];
            var key = [];
            var fileName = "";
            if(exceptionType == 1){

                fileName = "退款查询_" + $filter('date')(new Date(), 'yyyy-MM-dd');

                title = ['平台订单号', '商户号','商户名称','域名','商户订单号','收单账户',
                    '异常状态','订单金额','订单金额CNY','交易时间','退款金额',
                    '退款金额CNY','退款手续费','归还手续费','申请人','申请时间','申请理由','审核人','审核时间','审核结果'];
                key = ['orderId', 'merId','merName','siteUrl','merOrderId','aquireAccountName','type',
                    'sourceAmount','sourceRmbAmount','tradeTime','amount','rmbAmount','fee',
                    'returnFee','applicant','applicationTime','reasons','auditor','auditTime','status'];

            }else if(exceptionType == 2){

                fileName = "拒付查询_" + $filter('date')(new Date(), 'yyyy-MM-dd');
                title = ['平台订单号', '商户号','商户名称','域名','商户订单号','收单账户','异常状态','订单金额','订单金额CNY',
                    '交易时间','拒付金额','拒付金额CNY','拒付处理费','申请人','申请时间','申请理由','审核人','审核时间','审核结果'];



                key = ['orderId', 'merId','merName','siteUrl','merOrderId','aquireAccountName','type','sourceAmount',
                    'sourceRmbAmount','tradeTime','amount','rmbAmount','fee','applicant','applicationTime','reasons','auditor','auditTime','status'];

            }

            var csvData = {
                'data': value.orderChangeList,
                'fileName': fileName,
                'columns': {
                    'title':title,
                    'key': key,
                    'formatter':function(key,value){
                        if(key == "type"){

                            if(exceptionType == 1){

                                value =  $filter('enumParamsFilter')(value,[{2:"全额退款",3:"部分退款"}]);

                            }else if(exceptionType == 2){

                                value =  $filter('enumParamsFilter')(value,[{4:"全额拒付",5:"部分拒付",6:"代理拒付"}]);

                            }


                        }else if(key == "status"){

                            value =  $filter('enumParamsFilter')(value, [{1:"已通过"}]);


                        }else if(key == "tradeTime" || key == "applicationTime" || key == "auditTime"){

                            value = $filter('date')(value, "yyyy-MM-dd hh:mm:ss");

                        }


                        if(value == null || value == undefined){

                            value = "无";

                        }

                        return value;

                    }
                },

            };

            if (csvExp.export(csvData)) {
                toaster.pop({
                    type: 'success',
                    title: '异常单查询',
                    body: '异常单导出成功！'
                });
            } else {
                toaster.pop({
                    type: 'waring',
                    title: '异常单查询',
                    body: '异常单导出失败：条件搜索结果为空！'
                });
            }
        });
    }

}


// 退款拒付查询
function transInfoCtrlAA($scope, $timeout, $uibModal, $document, $filter, toaster, NgTableParams, httpSvc, csvExp) {
    $scope.merTips = false;
    $scope.minText = 3;
    $scope.orderTypeTxt = '平台订单号';
    $scope.orderType = 'orderId';
    $scope.init = null;
    var merWeb = [];
    var searchInfo = null;

    httpSvc.getData('post', '/trans/getInquireInit').then(function (value) {
        $scope.merchants = value.merchants;
        $scope.siteUrls = value.siteUrls;
        $scope.exceptionStatusI = value.exceptionStatusI;
        $scope.acquirerAccounts = value.acquirerAccounts;
        $scope.payModes = value.payModes;
        $scope.payTypes = value.payTypes;
        $scope.bankStatusI = value.bankStatusI;
        $scope.shipStatusI = value.shipStatusI;
        $scope.financeStatusI = value.financeStatusI;
        $scope.init = value;
    });

    $timeout(function () {
        $scope.$watch('startDate', function (newVal) {
            if (newVal !== '' && newVal !== undefined && newVal != null) {
                $scope.dateOptions2.minDate = $scope.startDate;
                $scope.endDateDisable = false;
                if (oldEndDate !== '') {
                    $scope.endDate = oldEndDate;
                }
            } else {
                $scope.endDateDisable = true;
                oldEndDate = $scope.endDate;
                $scope.endDate = '';
            }
        });

        $scope.$watch('init', function (newVal) {
            if (newVal !== undefined && newVal != null) {
                $scope.transTable = new NgTableParams({}, {
                    getData: function (params) {
                        angular.element('.ibox-content').addClass('sk-loading');
                        return httpSvc.getData('post', '/trans/getTransInfo', {
                            pageNum: params.page(),
                            pageSize: params.count(),
                            orderBy: params.sorting(),
                            searchInfo: searchInfo
                        }).then(function (value) {
                            params.total(value.total);
                            for (var i = 0; i < value.rows.length; i++) {
                                for (var j = 0; j < $scope.merchants.length; j++) {
                                    if (value.rows[i].merId === $scope.merchants[j].id) {
                                        value.rows[i]['merName'] = value.rows[i].merId + '(' + $scope.merchants[j].name + ')';
                                        break;
                                    }
                                }
                                for (var j = 0; j < $scope.siteUrls.length; j++) {
                                    if (value.rows[i].siteId === $scope.siteUrls[j].id) {
                                        value.rows[i]['siteUrl'] = $scope.siteUrls[j].siteUrl;
                                        break;
                                    }
                                }
                                for (var j = 0; j < $scope.acquirerAccounts.length; j++) {
                                    if (value.rows[i].accountId === $scope.acquirerAccounts[j].id) {
                                        value.rows[i]['accountName'] = $scope.acquirerAccounts[j].name;
                                        break;
                                    }
                                }
                            }
                            $scope.totalItems = value.total;
                            $scope.totalCurrency = value.customize.totalCurrency;
                            $scope.totalSuccess = value.customize.totalSuccess;
                            $scope.totalAmount = value.customize.totalAmount;
                            $scope.totalSAmount = value.customize.totalSAmount;
                            angular.element('.ibox-content').removeClass('sk-loading');
                            return value.rows;
                        });
                    }
                });
            }
        });
    });

    $scope.orderSwitch = function ($event, orderType) {
        $scope.orderTypeTxt = angular.element($event.target).text();
        $scope.orderType = orderType;
    };

    // Datepicker
    var oldEndDate = '';
    $scope.endDateDisable = true;

    $scope.format = 'yyyy/MM/dd';
    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.altInputFormats = ['yyyy/MM/dd'];
    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };

    $scope.searchOrder = function (data) {
        if (data != null) {
            if (data.siteId !== undefined && data.siteId != null) {
                for (var i = 0, j = $scope.init.siteUrls.length; i < j; i++) {
                    if ($scope.init.siteUrls[i].siteUrl === data.siteId) {
                        data.siteId = $scope.init.siteUrls[i].id;
                        break;
                    }
                }
            }
        }
        searchInfo = data;
        $scope.transTable.reload();
        $scope.transTable.page(1);
    };

    $scope.resetForm = function () {
        angular.element('#order_id').val('');
        angular.element('#mer_id_value').val('');
        angular.element('#mer_web_value').val('');
        angular.element('#email').val('');
        angular.element('#exception_status').val('');
        angular.element('#acquirer_account').val('');
        angular.element('#pay_mode').val('');
        angular.element('#pay_type').val('');
        angular.element('#bank_status').val('');
        angular.element('#ship_status').val('');
        angular.element('#finance_status').val('');
        angular.element('#ip_num').val('');
        angular.element('#start_date').val('');
        angular.element('#end_date').val('');
        $scope.dateOptions1 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.dateOptions2 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        searchInfo = null;
        $scope.$broadcast('angucomplete-alt:clearInput');
        $scope.transTable.reload();
        $scope.transTable.page(1);
    };

    // angular Modal
    $scope.showModal = function (order) {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/trans_modal',
            controller: 'transModalCtrl',
            size: 'lg',
            resolve: {
                orderInfo: order
            }
        });
        modalInstance.result.then(function () {

        }, function () {

        });
    };

    // export csv
    $scope.exportCsv = function () {
        httpSvc.getData('post', '/trans/getExport', searchInfo).then(function (value) {
            var csvData = {
                'data': value,
                'fileName': $filter('date')(new Date(), 'yyyyMMddhhmm'),
                'columns': {
                    'title': ['订单号', '商户订单号'],
                    'key': ['id', 'merId']
                }
            };
            if (csvExp.export(csvData)) {
                toaster.pop({
                    type: 'success',
                    title: '订单查询',
                    body: '订单导出成功！'
                });
            } else {
                toaster.pop({
                    type: 'waring',
                    title: '订单查询',
                    body: '订单导出失败：条件搜索结果为空！'
                });
            }
        });
    }
}


// 交易汇率
function tradeRateInfoCtrl($scope, $uibModal, $document, $filter, toaster, NgTableParams, httpSvc, csvExp) {

    var searchInfo = null;
    $scope.searchTradeRate = function (data) {
        searchInfo = data;
        $scope.tradeRateTable.page(1);
        $scope.tradeRateTable.reload();
    };

    httpSvc.getData('post', '/tradeRate/getTradeRateInit').then(function (value) {

        $scope.selectCurrencys = value.selectCurrencys;

    });

    $scope.tradeRateTable = new NgTableParams({}, {
        getData: function (params) {
            angular.element('.ibox-content').addClass('sk-loading');
            return httpSvc.getData('post', '/tradeRate/getTradeRateInfo', {
                pageFirst: params.page()-1,
                pageSize: params.count(),
                sortFieldName:"create_time",
                sortType:"desc",
                merId: "0",
                status:$("#status option:selected").val(),
                type: angular.element("#type").val(),
                searchInfo:searchInfo
            }).then(function (value) {

                $scope.totalItems = value.resultTotal;
                $scope.selectCurrencys = value.currency;
                params.total(value.resultTotal);
                angular.element('.ibox-content').removeClass('sk-loading');

                return value.tradeRateList;

            });
        }
    });

    $scope.isShow = true;

    $scope.optionMouseOver = function($event){


        angular.element($event.target).parent().val("String");


    }

    $scope.optionMouseClick = function($event){

        angular.element($event.target).parent().attr("size",0);
        var id = angular.element($event.target).parent().attr("id");
        angular.element("#selectInputDiv_" + id ).remove();


    }

    // 选择框的限制条数
    var idSave = "";
    $scope.selectMouseDown = function($event){

        var id = angular.element($event.target).attr("id");
        var size = angular.element($event.target).attr("size");
        if(size == undefined){

            size = 7;

        }
        if(id !== undefined){

            idSave = id;
            angular.element($event.target).attr("size","7");


        }else{

            angular.element($event.target).attr("size","0");

        }

        if(id == undefined || size == 7){

            len = 1;

        }else{

            len = 0

        }

        if(len == 0){

            var addHtml = '<div id="selectInputDiv_' + idSave + '" class="align-middle" ><img src="img/arrow/arrow.png" class="select-arrow" /><input type="text" id="selectInput" name="selectInput" class="form-control limit-height" /></div>';
            angular.element($event.target).before(addHtml);

        }



    }


    $scope.selectSourceCurrencyChange = function(){

        angular.element("#sourceCurrency").attr("size",0);
        $("#selectInputDiv_sourceCurrency").remove();

    }

    $scope.selectTargetCurrencyChange = function(){

        angular.element("#targetCurrency").attr("size",0);
        $("#selectInputDiv_targetCurrency").remove();

    }


    $scope.selectBlur = function($event){

        var id = angular.element($event.target).attr("id");
        angular.element($event.target).attr("size","0");
        var selectValue = angular.element("#" + id).val();

        if(id == undefined){

            len = 1;

        }else{

            len = 0

        }


        var len = angular.element("#selectInputDiv_" + id).length;

        if(len > 0){

            angular.element("#selectInputDiv_" + id).remove();

        }

    }


    $scope.$watch('minCreateTime', function (newVal) {
        if (newVal !== '' && newVal !== undefined && newVal != null) {
            $scope.dateOptions2.minDate = $scope.minCreateTime;
            $scope.maxCreateTimeDisable = false;
            if (oldCreateTime !== '') {
                $scope.maxCreateTime = oldCreateTime;
            }
        } else {
            $scope.maxCreateTimeDisable = true;
            oldCreateTime = $scope.maxCreateTime;
            $scope.maxCreateTime = '';
        }
    });

    $scope.$watch('minModifyTime', function (newVal) {
        if (newVal !== '' && newVal !== undefined && newVal != null) {
            $scope.dateOptions4.minDate = $scope.minModifyTime;
            $scope.maxModifyTimeDisable = false;
            if (oldModifyTime !== '') {
                $scope.maxModifyTime = oldModifyTime;
            }
        } else {
            $scope.maxModifyTimeDisable = true;
            oldModifyTime = $scope.maxModifyTime;
            $scope.maxModifyTime = '';
        }
    });

    var oldCreateTime= '';
    var oldModifyTime= '';
    $scope.maxCreateTimeDisable = true;

    $scope.format = 'yyyy/MM/dd';

    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1
    };

    $scope.dateOptions3 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions4 = {
        formatYear: 'yyyy',
        startingDay: 1
    };

    $scope.altInputFormats = ['yyyy/MM/dd'];

    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };


    $scope.popup3 = {

        opend: false
    };

    $scope.openDatepicker3 = function () {
        $scope.popup3.opend = !$scope.popup3.opend;
    };

    $scope.popup4 = {
        opend: false
    };

    $scope.openDatepicker4 = function () {
        $scope.popup4.opend = !$scope.popup4.opend;
    };


    $scope.resetForm = function () {

        $scope.tradeRateTable.page(1);
        $scope.tradeRateTable.reload();
    };

    var idArr = [];
    $scope.delDisabled = true;
    $scope.collectSelectRows = function($event,id){

        var isChecked = angular.element($event.target).prop("checked");

        if(isChecked == true){

            idArr.push(id);
            $scope.delDisabled = false;

        }else{

            idArr.remove(id);

        }

        if(idArr.length == 0){

            $scope.delDisabled = true;

        }

    }


    $scope.showAddModal = function () {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/exchangeRateSection/tradeRateAdd',
            controller: 'tradeRateInfoAddModalCtrl',
            resolve: {

                selectCurrencys: function () {

                    return $scope.selectCurrencys

                },
                type: function () {

                    return angular.element("#type").val();

                }
            }
        });
        modalInstance.result.then(function () {

            $scope.tradeRateTable.page(1);
            $scope.tradeRateTable.reload();

        }, function () {

            $scope.tradeRateTable.page(1);
            $scope.tradeRateTable.reload();

        });
    };

    // 编辑
    $scope.showEditModal = function (editObj) {

        var modalInstance = $uibModal.open({
            templateUrl: '/views/exchangeRateSection/tradeRateUpdate',
            controller: 'tradeRateInfoEditModalCtrl',
            resolve: {

                editObj: function () {
                    return editObj;
                },
                selectCurrencys:function(){

                    return $scope.selectCurrencys

                },
                type:function(){

                    return angular.element("#type").val();

                }
            }
        });

        modalInstance.result.then(function () {

            $scope.tradeRateTable.page(1);
            $scope.tradeRateTable.reload();


        }, function () {

            $scope.tradeRateTable.page(1);
            $scope.tradeRateTable.reload();

        });
    };

    // 批量删除
    $scope.batchDel = function(){

        var ids = idArr.join(",");
        httpSvc.getData('post','/tradeRate/batchDel',{

            id:ids,
            merId:"0",
            type:angular.element("#type").val()

        }).then(function (value) {

            if(value.result == 1){

                toaster.pop({
                    type: 'success',
                    title: '汇率删除',
                    body: '删除成功！'
                });

            }else{

                toaster.pop({
                    type: 'error',
                    title: '汇率删除',
                    body: '删除失败！'
                });

            }

            idArr = [];

            $scope.tradeRateTable.page(1);
            $scope.tradeRateTable.reload();


        });


        $scope.delDisabled = true;


    }

    // 列表导出
    $scope.exportCsv = function ( ) {

        var type = angular.element("#type").val();
        var fileName = "";
        if(type == 0){

            fileName = "交易汇率_" + $filter('date')(new Date(), 'yyyy-MM-dd');

        }else if(type == 2){

            fileName = "划款汇率_" + $filter('date')(new Date(), 'yyyy-MM-dd');

        }

        httpSvc.getData('post', '/tradeRate/getTradeRateInfo', {
            merId: "0",
            type:angular.element("#type").val(),
            searchInfo:searchInfo
        }).then(function (value) {
            var csvData = {
                'data':value.tradeRateList,
                'fileName': fileName,
                'columns': {
                    'title': ['原始币种', '目标币种','汇率','创建人','创建时间','修改人','修改时间'],
                    'key': ['sourceCurrency', 'targetCurrency','rate','creator','createTime','modifier','modifyTime'],
                    'formatter':function(key,value){

                        if(key == "createTime" || key == "modifyTime"){

                            value = $filter('date')(value, "yyyy-MM-dd hh:mm:ss");

                        }

                        if(value == null || value == undefined){

                            value = "无";

                        }

                        return value;

                    }
                }
            };
            if (csvExp.export(csvData)) {
                toaster.pop({
                    type: 'success',
                    title: '交易汇率查询',
                    body: '交易汇率导出成功！'
                });
            } else {
                toaster.pop({
                    type: 'waring',
                    title: '交易汇率查询',
                    body: '交易汇率导出失败：条件搜索结果为空！'
                });
            }
        });
    }
}



// 添加系统常量配置
function tradeRateInfoAddModalCtrl($scope, $uibModalInstance, httpSvc, toaster,selectCurrencys,type) {

    $scope.isSourceCurrencyFillError = true;
    $scope.isTargetCurrencyFillError = true;
    $scope.isRateFillError = true;

    $scope.selectCurrencys = selectCurrencys;

    $scope.addIsDisabled = true;
    $scope.addRateIsDisabled = true;

    $scope.back = function () {

        $uibModalInstance.dismiss();

    };

    $scope.optionMouseOver = function($event){


        angular.element($event.target).parent().val("String");


    }

    $scope.optionMouseClick = function($event){

        angular.element($event.target).parent().attr("size",0);
        var id = angular.element($event.target).parent().attr("id");
        angular.element("#selectInputDiv_" + id ).remove();


    }

    $scope.rateFocus = function(){

        $scope.addRateIsDisabled = false;
        angular.element("#rate").removeClass("has-error");
        angular.element("#rate").addClass("has-success");
        angular.element("input:not(#rate)").removeClass("has-success");
        angular.element("select:not(#rate)").removeClass("has-success");

    }

    $scope.rateBlur = function(){

        var rate = angular.element("#rate").val();
        if(null == rate || rate == "" || !/^\d+(\.\d+)?$/.test(rate)){

            $scope.addRateIsDisabled = true;
            angular.element("#rate").addClass("has-error");
            angular.element("#rate").removeClass("has-success");

        }

    }

    var idSave = "";

    $scope.selectMouseDown = function($event){

        var id = angular.element($event.target).attr("id");
        var size = angular.element($event.target).attr("size");
        if(size == undefined){

            size = 7;

        }
        if(id !== undefined){

            idSave = id;

        }

        angular.element($event.target).attr("size","7");
        angular.element("input:not(#"+ id +")").removeClass("has-success");
        angular.element("select:not(#"+ id +")").removeClass("has-success");

        if(id == undefined || size == 7){

            len = 1;

        }else{

            len = 0

        }

        if(len == 0){

            var addHtml = '<div id="selectInputDiv_' + idSave + '" class="align-middle" ><img src="img/arrow/arrow.png" class="select-arrow" /><input type="text" id="selectInput" name="selectInput" class="form-control limit-height" /></div>';
            angular.element($event.target).before(addHtml);

        }

        var selectValue = angular.element("#" + id).val();
        var promptId = id + "Prompt";

        if(promptId == "sourceCurrencyPrompt"){

            angular.element("#" + id + "Prompt").removeClass("select-prompt");
            angular.element("#" + id + "Prompt").addClass("no-select-prompt");

        }else if(promptId == "targetCurrencyPrompt"){

            angular.element("#" + id + "Prompt").removeClass("select-prompt-md");
            angular.element("#" + id + "Prompt").addClass("no-select-prompt");

        }


    }

    $scope.selectBlur = function($event){

        var id = angular.element($event.target).attr("id");
        angular.element($event.target).attr("size","0");
        var selectValue = angular.element("#" + id).val();
        var promptId = id + "Prompt";

        var len = angular.element("#selectInputDiv_" + id).length;

        if(len > 0){

            angular.element("#selectInputDiv_" + id).remove();

        }

        if(null == selectValue || selectValue == ""){

            angular.element("#" + id ).addClass("has-error");
            angular.element("#" + id ).removeClass("has-success");
            if(promptId == "sourceCurrencyPrompt"){

                angular.element("#" + id + "Prompt").addClass("select-prompt");
                angular.element("#" + id + "Prompt").removeClass("no-select-prompt");

            }else if(promptId == "targetCurrencyPrompt"){

                angular.element("#" + id + "Prompt").addClass("select-prompt-md");
                angular.element("#" + id + "Prompt").removeClass("no-select-prompt");

            }

            $scope.addIsDisabled = true;

        }else{

            angular.element("#" + id ).removeClass("has-error");
            angular.element("#" + id ).addClass("has-success");
            if(promptId == "sourceCurrencyPrompt"){

                angular.element("#" + id + "Prompt").removeClass("select-prompt");
                angular.element("#" + id + "Prompt").addClass("no-select-prompt");

            }else if(promptId == "targetCurrencyPrompt"){

                angular.element("#" + id + "Prompt").removeClass("select-prompt-md");
                angular.element("#" + id + "Prompt").addClass("no-select-prompt");

            }

            $scope.addIsDisabled = false;

        }

    }


    $scope.sourceCurrencyChange = function(){

        var selectValue = angular.element("#sourceCurrency").val();
        angular.element("#sourceCurrency").attr("size","0");
        if(null == selectValue || selectValue == ""){

            angular.element("#sourceCurrency").addClass("has-error");
            angular.element("#sourceCurrency").removeClass("has-success");

            angular.element("#sourceCurrencyPrompt").addClass("select-prompt");
            angular.element("#sourceCurrencyPrompt").removeClass("no-select-prompt");

            $scope.addIsDisabled = true;

        }else{

            angular.element("#sourceCurrency").removeClass("has-error");
            angular.element("#sourceCurrency").addClass("has-success");

            angular.element("#sourceCurrencyPrompt").removeClass("select-prompt");
            angular.element("#sourceCurrencyPrompt").addClass("no-select-prompt");
            $scope.addIsDisabled = false;

        }

        angular.element("input:not(#sourceCurrency)").removeClass("has-success");
        angular.element("select:not(#sourceCurrency)").removeClass("has-success");
        $("#selectInputDiv_sourceCurrency").remove();

    }


    $scope.targetCurrencyChange = function(){

        var selectValue = angular.element("#targetCurrency").val();
        angular.element("#targetCurrency").attr("size","0");
        if(null == selectValue || selectValue == ""){

            angular.element("#targetCurrency").addClass("has-error");
            angular.element("#targetCurrency").removeClass("has-success");

            angular.element("#targetCurrencyPrompt").addClass("select-prompt-md");
            angular.element("#targetCurrencyPrompt").removeClass("no-select-prompt");
            $scope.addIsDisabled = true;

        }else{

            angular.element("#targetCurrency").removeClass("has-error");
            angular.element("#targetCurrency").addClass("has-success");

            angular.element("#targetCurrencyPrompt").removeClass("select-prompt-md");
            angular.element("#targetCurrencyPrompt").addClass("no-select-prompt");
            $scope.addIsDisabled = false;

        }

        angular.element("input:not(#targetCurrency)").removeClass("has-success");
        angular.element("select:not(#targetCurrency)").removeClass("has-success");
        $("#selectInputDiv_targetCurrency").remove();

    }


    $scope.generalFocus = function($event){

        $scope.addIsDisabled = false;
        var id = angular.element($event.target).attr("id");
        angular.element("input:not(#"+ id +")").removeClass("has-success");
        angular.element("select:not(#"+ id +")").removeClass("has-success");

    }


    $scope.addTradeRate = function(){
        var obj = angular.element("#tradeRateObjForm").serializeJson();
        obj.merId = "0";
        obj.type = type;
        obj.status = "0";
        httpSvc.getData('post','/tradeRate/save',obj).then(function (value) {

            if(value.success == 1){

                toaster.pop({
                    type: 'success',
                    title: '汇率添加',
                    body: '添加成功！'
                });

            }else{

                var msg = "添加失败！";
                if(value.msg != ""){

                    msg = msg + value.msg;

                }

                toaster.pop({
                    type: 'error',
                    title: '汇率添加',
                    body: msg
                });

            }

            $uibModalInstance.dismiss();

        });

        $scope.addIsDisabled = true;

    }


}


// 编辑汇率配置
function tradeRateInfoEditModalCtrl($scope, $uibModalInstance, httpSvc, toaster,editObj,selectCurrencys,type) {

    $scope.updateIsDisabled = true;

    $scope.tradeRate = editObj;

    $scope.selectCurrencys = selectCurrencys;


    $scope.back = function () {

        $uibModalInstance.dismiss();

    };

    $scope.optionMouseOver = function($event){


        angular.element($event.target).parent().val("String");


    }

    $scope.optionMouseClick = function($event){

        angular.element($event.target).parent().attr("size",0);
        var id = angular.element($event.target).parent().attr("id");
        angular.element("#selectInputDiv_" + id ).remove();


    }

    $scope.rateFocus = function(){

        $scope.updateIsDisabled = false;
        angular.element("#rate").removeClass("has-error");
        angular.element("#rate").addClass("has-success");
        angular.element("input:not(#rate)").removeClass("has-success");
        angular.element("select:not(#rate)").removeClass("has-success");

    }

    $scope.rateBlur = function(){

        var rate = angular.element("#rate").val();
        if(null == rate || rate == "" || !/^\d+(\.\d+)?$/.test(rate)){

            $scope.updateIsDisabled = true;
            angular.element("#rate").addClass("has-error");
            angular.element("#rate").removeClass("has-success");

        }

    }

    var idSave = "";

    $scope.selectMouseDown = function($event){

        var id = angular.element($event.target).attr("id");
        var size = angular.element($event.target).attr("size");
        if(id !== undefined){

            idSave = id;

        }
        angular.element($event.target).attr("size","7");
        angular.element("input:not(#"+ id +")").removeClass("has-success");
        angular.element("select:not(#"+ id +")").removeClass("has-success");

        if(id == undefined || size == 7){

            len = 1;

        }else{

            len = 0

        }

        if(len == 0){

            var addHtml = '<div id="selectInputDiv_' + idSave + '" class="align-middle" ><img src="img/arrow/arrow.png" class="select-arrow" /><input type="text" id="selectInput" name="selectInput" class="form-control limit-height" /></div>';
            angular.element($event.target).before(addHtml);

        }

        if(promptId == "sourceCurrencyPrompt"){

            angular.element("#" + id + "Prompt").removeClass("select-prompt");
            angular.element("#" + id + "Prompt").addClass("no-select-prompt");

        }else if(promptId == "targetCurrencyPrompt"){

            angular.element("#" + id + "Prompt").removeClass("select-prompt-md");
            angular.element("#" + id + "Prompt").addClass("no-select-prompt");

        }

    }


    $scope.sourceCurrencyChange = function(){

        var selectValue = angular.element("#sourceCurrency").val();
        angular.element("#sourceCurrency").attr("size","0");
        if(null == selectValue || selectValue == ""){

            angular.element("#sourceCurrency").addClass("has-error");
            angular.element("#sourceCurrency").removeClass("has-success");

            angular.element("#sourceCurrencyPrompt").addClass("select-prompt");
            angular.element("#sourceCurrencyPrompt").removeClass("no-select-prompt");

            $scope.updateIsDisabled = true;

        }else{

            angular.element("#sourceCurrency").removeClass("has-error");
            angular.element("#sourceCurrency").addClass("has-success");

            angular.element("#sourceCurrencyPrompt").removeClass("select-prompt");
            angular.element("#sourceCurrencyPrompt").addClass("no-select-prompt");

            $scope.updateIsDisabled = false;

        }

        angular.element("input:not(#sourceCurrency)").removeClass("has-success");
        angular.element("select:not(#sourceCurrency)").removeClass("has-success");
        $("#selectInputDiv_sourceCurrency").remove();

    }


    $scope.targetCurrencyChange = function(){

        var selectValue = angular.element("#targetCurrency").val();
        angular.element("#targetCurrency").attr("size","0");
        if(null == selectValue || selectValue == ""){

            angular.element("#targetCurrency").addClass("has-error");
            angular.element("#targetCurrency").removeClass("has-success");

            angular.element("#targetCurrencyPrompt").addClass("select-prompt-md");
            angular.element("#targetCurrencyPrompt").removeClass("no-select-prompt");

            $scope.updateIsDisabled = true;

        }else{

            angular.element("#targetCurrency").removeClass("has-error");
            angular.element("#targetCurrency").addClass("has-success");

            angular.element("#targetCurrencyPrompt").removeClass("select-prompt-md");
            angular.element("#targetCurrencyPrompt").addClass("no-select-prompt");

            $scope.updateIsDisabled = false;

        }

        angular.element("input:not(#targetCurrency)").removeClass("has-success");
        angular.element("select:not(#targetCurrency)").removeClass("has-success");
        $("#selectInputDiv_targetCurrency").remove();

    }


    $scope.selectBlur = function($event){

        var id = angular.element($event.target).attr("id");
        angular.element($event.target).attr("size","0");
        var selectValue = angular.element("#" + id ).val();
        var promptId = id + "Prompt";

        var len = angular.element("#selectInputDiv_" + id).length;
        if(len > 0){

            angular.element("#selectInputDiv_" + id).remove();

        }

        if(null == selectValue || selectValue == ""){

            angular.element("#" + id ).addClass("has-error");
            angular.element("#" + id ).removeClass("has-success");
            if(promptId == "sourceCurrencyPrompt"){

                angular.element("#" + id + "Prompt").addClass("select-prompt");
                angular.element("#" + id + "Prompt").removeClass("no-select-prompt");

            }else if(promptId == "targetCurrencyPrompt"){

                angular.element("#" + id + "Prompt").addClass("select-prompt-md");
                angular.element("#" + id + "Prompt").removeClass("no-select-prompt");

            }

        }else{

            angular.element("#" + id ).removeClass("has-error");
            angular.element("#" + id ).addClass("has-success");
            if(promptId == "sourceCurrencyPrompt"){

                angular.element("#" + id + "Prompt").removeClass("select-prompt");
                angular.element("#" + id + "Prompt").addClass("no-select-prompt");

            }else if(promptId == "targetCurrencyPrompt"){

                angular.element("#" + id + "Prompt").removeClass("select-prompt-md");
                angular.element("#" + id + "Prompt").addClass("no-select-prompt");

            }

        }

    }

    $scope.generalFocus = function($event){

        $scope.updateIsDisabled = false;
        var id = angular.element($event.target).attr("id");
        angular.element("input:not(#"+ id +")").removeClass("has-success");
        angular.element("select:not(#"+ id +")").removeClass("has-success");

    }

    $scope.updateTradeRate = function(){

        var obj = angular.element("#tradeRateObjForm").serializeJson();
        obj.merId = "0";
        obj.type = type;
        obj.status = "0";
        httpSvc.getData('post','/tradeRate/update',obj).then(function (value) {

            if(value.success == 1){

                toaster.pop({
                    type: 'success',
                    title: '汇率编辑',
                    body: '更新成功！'
                });

            }else{

                var msg = "更新失败！";
                if(value.msg != ""){

                    msg = msg + value.msg;

                }

                toaster.pop({
                    type: 'error',
                    title: '汇率编辑',
                    body: msg
                });


            }

            $uibModalInstance.dismiss();

        });

        $scope.updateIsDisabled = true;

    }


}


// 通道汇率
function channelRateInfoCtrl($scope, $uibModal, $document, $filter, toaster, NgTableParams, httpSvc, csvExp,$timeout,$http) {

    var searchInfo = null;
    angular.element("#generalTypeValue").show();
    angular.element("#currencyTypeValue").hide();
    angular.element("#siteTypeValue").hide();

    $scope.searchChannelRate = function (data) {

        searchInfo = data;
        $scope.channelRateTable.page(1);
        $scope.channelRateTable.reload();
    };

    httpSvc.getData('post', '/channelRate/getChannelRateInit',3).then(function (value) {
        $scope.merchants = value.merchants;

    });

    $scope.typeChange = function(){

        var type = angular.element("#type").val();

        if(type !== undefined && type != null && type !=""){

            if(type == 0 ){

                angular.element("#generalTypeValue").val("0");
                angular.element("#generalTypeValue").show();
                angular.element("#currencyTypeValue").hide();
                angular.element("#siteTypeValue").hide();

            }else if(type == 1){

                angular.element("#currencyTypeValue").show();
                angular.element("#generalTypeValue").hide();
                angular.element("#siteTypeValue").hide();


            }else if(type == 2){


                angular.element("#generalTypeValue").hide();
                angular.element("#currencyTypeValue").hide();
                angular.element("#siteTypeValue").show();
                angular.element("#siteTypeValue .angucomplete-dropdown").hide();

                var elementValue = angular.element("input[name='elementValue']").val();
                if(elementValue !== "" && elementValue !== undefined && elementValue !== null){

                    angular.element("#siteTypeValue .angucomplete-dropdown").show();

                    httpSvc.getData('post', '/channelRate/getSitesByParamInit',{merId:elementValue}).then(function (value) {

                        $scope.websites = value.merWebsites;
                        $scope.webDisable = false;
                        $scope.minText = 0;

                    });

                }


            }


            if(type == 1){

                httpSvc.getData('post', '/channelRate/getChannelRateInit',type).then(function (value) {

                    $scope.selectCurrencys = value.selectCurrencys;

                });

            }


        }


    }

    $scope.elementValueChange = function(){

        var elementValue = angular.element("input[name='elementValue']").val();
        var type = angular.element("#type").val();
        if(elementValue !== "" && elementValue !== undefined && elementValue !== null && type == 2){

            angular.element("#siteTypeValue .angucomplete-dropdown").show();

            httpSvc.getData('post', '/channelRate/getSitesByParamInit',{merId:elementValue}).then(function (value) {

                $scope.websites = value.merWebsites;
                $scope.webDisable = false;
                $scope.minText = 0;

            });

        }else{

            if(type == 2 && (elementValue == "" || elementValue == undefined || elementValue == null)){

                angular.element("#siteTypeValue").find("option:gt(0)").remove();

            }

        }

    }

    $scope.channelRateTable = new NgTableParams({}, {
        getData: function (params) {
            angular.element('.ibox-content').addClass('sk-loading');

            return httpSvc.getData('post', '/channelRate/getChannelRateInfo', {

                pageFirst: params.page()-1,
                pageSize: params.count(),
                sortFieldName:"create_time",
                sortType:"desc",
                searchInfo:searchInfo
            }).then(function (value) {

                params.total(value.resultTotal);
                $scope.totalItems = value.resultTotal;
                angular.element('.ibox-content').removeClass('sk-loading');
                return value.channelRateList;

            });
        }
    });

    $scope.$watch('minCreateTime', function (newVal) {
        if (newVal !== '' && newVal !== undefined && newVal != null) {
            $scope.dateOptions2.minDate = $scope.minCreateTime;
            $scope.maxCreateTimeDisable = false;
            if (oldCreateTime !== '') {
                $scope.maxCreateTime = oldCreateTime;
            }
        } else {
            $scope.maxCreateTimeDisable = true;
            oldCreateTime = $scope.maxCreateTime;
            $scope.maxCreateTime = '';
        }
    });

    $scope.$watch('minModifyTime', function (newVal) {
        if (newVal !== '' && newVal !== undefined && newVal != null) {
            $scope.dateOptions4.minDate = $scope.minModifyTime;
            $scope.maxModifyTimeDisable = false;
            if (oldModifyTime !== '') {
                $scope.maxModifyTime = oldModifyTime;
            }
        } else {
            $scope.maxModifyTimeDisable = true;
            oldModifyTime = $scope.maxModifyTime;
            $scope.maxModifyTime = '';
        }
    });

    var oldCreateTime= '';
    var oldModifyTime= '';
    $scope.maxCreateTimeDisable = true;

    $scope.format = 'yyyy/MM/dd';

    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1
    };

    $scope.dateOptions3 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions4 = {
        formatYear: 'yyyy',
        startingDay: 1
    };

    $scope.altInputFormats = ['yyyy/MM/dd'];

    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };


    $scope.popup3 = {

        opend: false
    };

    $scope.openDatepicker3 = function () {
        $scope.popup3.opend = !$scope.popup3.opend;
    };

    $scope.popup4 = {
        opend: false
    };

    $scope.openDatepicker4 = function () {
        $scope.popup4.opend = !$scope.popup4.opend;
    };

    $scope.resetForm = function () {

        angular.element('#type').val('');
        angular.element('select[name="typeValue"]').val('');
        angular.element('#minCreateTime').val('');
        angular.element('#maxCreateTime').val('');
        angular.element('#elementValue').val('');
        angular.element('#minModifyTime').val('');
        angular.element('#maxModifyTime').val('');
        angular.element('#creator').val('');
        angular.element('#modifier').val('');
        angular.element('#siteTypeValue').val('');

        $scope.dateOptions1 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.dateOptions2 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.dateOptions3 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.dateOptions4 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        searchInfo = null;

        angular.element("#siteTypeValue .angucomplete-dropdown").hide();
        $scope.type = "";
        $scope.maxCreateTimeDisable = true;
        $scope.maxModifyTimeDisable = true;
        $scope.$broadcast('angucomplete-alt:clearInput');
        $scope.channelRateTable.page(1);
        $scope.channelRateTable.reload();
    };


    var idArr = [];
    $scope.delDisabled = true;
    $scope.collectSelectRows = function($event,id){

        var isChecked = angular.element($event.target).prop("checked");

        if(isChecked == true){

            idArr.push(id);
            $scope.delDisabled = false;

        }else{

            idArr.remove(id);

        }

        if(idArr.length == 0){

            $scope.delDisabled = true;

        }

    }


    $scope.showAddModal = function () {
        var modalInstance = $uibModal.open({
            templateUrl: '/views/exchangeRateSection/channelRateAdd',
            controller: 'channelRateInfoAddModalCtrl',
            resolve: {

                selectMerchants:function(){

                    return $scope.merchants

                }

            }
        });
        modalInstance.result.then(function () {

            $scope.channelRateTable.page(1);
            $scope.channelRateTable.reload();

        }, function () {

            $scope.channelRateTable.page(1);
            $scope.channelRateTable.reload();

        });
    };

    // 编辑
    $scope.showEditModal = function (editObj) {

        var modalInstance = $uibModal.open({
            templateUrl: '/views/exchangeRateSection/channelRateUpdate',
            controller: 'channelRateInfoEditModalCtrl',
            resolve: {

                editObj: function () {
                    return editObj;
                },
                selectMerchants:function(){

                    return $scope.merchants

                }
            }
        });

        modalInstance.result.then(function () {

            $scope.channelRateTable.page(1);
            $scope.channelRateTable.reload();


        }, function () {

            $scope.channelRateTable.page(1);
            $scope.channelRateTable.reload();

        });
    };

    // 批量删除
    $scope.batchDel = function(){

        var ids = idArr.join(",");
        httpSvc.getData('post','/channelRate/batchDel',{id:ids}).then(function (value) {

            if(value.result == 1){

                toaster.pop({
                    type: 'success',
                    title: '汇率删除',
                    body: '删除成功！'
                });

            }else{

                toaster.pop({
                    type: 'error',
                    title: '汇率删除',
                    body: '删除失败！'
                });

            }

            idArr = [];

            $scope.channelRateTable.page(1);
            $scope.channelRateTable.reload();


        });


        $scope.delDisabled = true;


    }

    // 列表导出
    $scope.exportCsv = function () {
        httpSvc.getData('post', '/channelRate/getChannelRateInfo', {

        }).then(function (value) {
            var csvData = {
                'data':value.channelRateList,
                'fileName': "通道汇率_" + $filter('date')(new Date(), 'yyyy-MM-dd'),
                'columns': {
                    'title': ['类型', '元素类型值','商户号','上抛点数','创建人','创建时间','修改人','修改时间'],
                    'key': ['type', 'typeValueName','elementValue','upPercent','creator','createTime','modifier','modifyTime'],
                    'formatter':function(key,value){

                        if(key == "type"){

                            value =  $filter('enumParamsFilter')(value, [{0:"通用",1:"原始币种",2:"域名"}]);

                        }else if(key == "createTime" || key == "modifyTime"){

                            value = $filter('date')(value, "yyyy-MM-dd hh:mm:ss");

                        }


                        if(value == null || value == undefined){

                            value = "无";

                        }

                        return value;

                    }
                }
            };
            if (csvExp.export(csvData)) {
                toaster.pop({
                    type: 'success',
                    title: '通道汇率查询',
                    body: '通道汇率导出成功！'
                });
            } else {
                toaster.pop({
                    type: 'waring',
                    title: '通道汇率查询',
                    body: '通道汇率导出失败：条件搜索结果为空！'
                });
            }
        });
    }
}


// 添加通道汇率
function channelRateInfoAddModalCtrl($scope, $uibModalInstance, httpSvc, toaster,selectMerchants) {
    $scope.isGeneralTypeValueSelect = true;
    $scope.isCurrencyTypeSelect = false;
    $scope.isSiteTypeSelect = false;

    $scope.merchants = selectMerchants;

    $scope.addIsDisabled = true;
    $scope.addTypeValueIsDisabled = true;
    $scope.addUpPercentIsDisabled = true;

    $scope.optionMouseOver = function($event){


        angular.element($event.target).parent().val("String");


    }

    $scope.optionMouseClick = function($event){

        angular.element($event.target).parent().attr("size",0);
        var id = angular.element($event.target).parent().attr("id");
        angular.element("#selectInputDiv_" + id ).remove();


    }

    $scope.typeChange = function(){

        var type = angular.element("#type").val();

        // 清空子类型数据
        $scope.typeValue = "";

        $scope.elementValue = "";

        angular.element("#elementValuePrompt").text("");

        if(type !== undefined && type != null && type !=""){

            if(type == 0 ){

                $scope.isGeneralTypeValueSelect = true;
                $scope.isCurrencyTypeSelect = false;
                $scope.isSiteTypeSelect = false;
                angular.element("#typeValuePrompt").text("需选择元素类型(必选)");
                angular.element("#elementValueLabelId").html('商户号:');


            }else if(type == 1){

                $scope.isGeneralTypeValueSelect = false;
                $scope.isCurrencyTypeSelect = true;
                $scope.isSiteTypeSelect = false;
                angular.element("#typeValuePrompt").text("需选择币种(必选)");
                angular.element("#elementValueLabelId").html('商户号:');

            }else if(type == 2){

                $scope.isGeneralTypeValueSelect = false;
                $scope.isCurrencyTypeSelect = false;
                $scope.isSiteTypeSelect = true;
                angular.element("#typeValuePrompt").text("请先选择商户号,再选择域名(必选)");
                angular.element("#elementValuePrompt").text("需选择商户号(必选)");
                angular.element("#elementValueLabelId").html('<font color="red">*</font>商户号:');
                $scope.addElementValueIsDisabled = true;

            }


            if(type == 1){

                httpSvc.getData('post', '/channelRate/getChannelRateInit',type).then(function (value) {

                    $scope.selectCurrencys = value.selectCurrencys;

                });

            }

            $scope.addIsDisabled = false;
            $scope.addTypeValueIsDisabled = true;
            angular.element("#typePrompt").removeClass("select-prompt");
            angular.element("#typePrompt").addClass("no-select-prompt");

        }else{

            $scope.isGeneralTypeValueSelect = true;
            $scope.isCurrencyTypeSelect = false;
            $scope.isSiteTypeSelect = false;
            $scope.addIsDisabled = true;
            angular.element("#typePrompt").addClass("select-prompt");
            angular.element("#typePrompt").removeClass("no-select-prompt");


        }

        angular.element("select:not(#type)").removeClass("has-success");
        angular.element("input").removeClass("has-success");

    }

    $scope.currencyTypeValueChange = function(){

        var selectValue = angular.element("#currencyTypeValue").val();
        angular.element("#selectInputDiv_currencyTypeValue").remove();
        angular.element("#currencyTypeValue").attr("size","0");

        if(null == selectValue || selectValue == ""){

            $scope.addTypeValueIsDisabled = true;
            angular.element("#typeValuePrompt").addClass("select-prompt-ms");
            angular.element("#typeValuePrompt").removeClass("no-select-prompt");

        }else{

            $scope.addTypeValueIsDisabled = false;
            angular.element("#typeValuePrompt").removeClass("select-prompt-ms");
            angular.element("#typeValuePrompt").addClass("no-select-prompt");

        }

        angular.element("select:not(#currencyTypeValue)").removeClass("has-success");
        $("#selectInputDiv_currencyTypeValue").remove();

    }

    $scope.generalTypeValueChange = function(){

        var selectValue = angular.element("#generalTypeValue").val();
        angular.element("#selectInputDiv_generalTypeValue").remove();
        if(null == selectValue || selectValue == ""){

            $scope.addTypeValueIsDisabled = true;
            angular.element("#typeValuePrompt").addClass("select-prompt-ms");
            angular.element("#typeValuePrompt").removeClass("no-select-prompt");


        }else{

            $scope.addTypeValueIsDisabled = false;
            angular.element("#typeValuePrompt").removeClass("select-prompt-ms");
            angular.element("#typeValuePrompt").addClass("no-select-prompt");

        }

        angular.element("select:not(#generalTypeValue)").removeClass("has-success");

    }


    $scope.siteTypeValueChange = function(){


        var selectValue = angular.element("#siteTypeValue").val();
        if(selectValue == "String"){

            angular.element("#siteTypeValue").val("");

        }

        angular.element("#siteTypeValue").attr("size","0");
        if(null == selectValue || selectValue == ""){

            $scope.addTypeValueIsDisabled = true;
            angular.element("#typeValuePrompt").addClass("select-prompt-ms");
            angular.element("#typeValuePrompt").removeClass("no-select-prompt");

        }else{

            $scope.addTypeValueIsDisabled = false;
            angular.element("#typeValuePrompt").removeClass("select-prompt-ms");
            angular.element("#typeValuePrompt").addClass("no-select-prompt");

        }

        angular.element("select:not(#siteTypeValue)").removeClass("has-success");
        angular.element("input").removeClass("has-error");

        angular.element("#selectInputDiv_siteTypeValue").remove();

    }

    $scope.elementValueChange = function(){
        var selectValue = angular.element("#elementValue").val();
        var type = angular.element("#type").val();
        angular.element("#elementValue").attr("size","0");
        if(selectValue == "" || selectValue == undefined || selectValue == null){

            angular.element("#elementValuePrompt").addClass("select-prompt-md");
            angular.element("#elementValuePrompt").removeClass("no-select-prompt");


        }else{

            angular.element("#elementValuePrompt").removeClass("select-prompt-md");
            angular.element("#elementValuePrompt").addClass("no-select-prompt");

        }

        var elementValue = angular.element("#elementValue").val();
        var type = angular.element("#type").val();

        if(selectValue !== "" && selectValue !== undefined && selectValue !== null && type == 2){
            httpSvc.getData('post', '/channelRate/getSitesByParamInit',{merId:elementValue}).then(function (value) {

                if( null !== value.merWebsites && value.merWebsites !== undefined){

                    $scope.websites = value.merWebsites;


                }


            });

            $scope.addIsDisabled = false;
            $scope.addElementValueIsDisabled = false;

        }else{

            if(type == 2 && (selectValue == "" || selectValue == undefined || selectValue == null)){

                angular.element("#siteTypeValue").find("option:gt(1)").remove();

            }

            $scope.addIsDisabled = true;
            $scope.addElementValueIsDisabled = true;

        }

        if(type != 2){

            $scope.addIsDisabled = false;
            $scope.addElementValueIsDisabled = false;

        }

        angular.element("select:not(#elementValue)").removeClass("has-success");

        $("#selectInputDiv_elementValue").remove();

    }

    $scope.back = function () {

        $uibModalInstance.dismiss();

    };

    $scope.upPercentFocus = function(){

        $scope.addUpPercentIsDisabled = false;
        angular.element("#upPercent").removeClass("has-error");
        angular.element("#upPercent").addClass("has-success");
        angular.element("input:not(#upPercent)").removeClass("has-success");
        angular.element("select:not(#upPercent)").removeClass("has-success");


    }

    $scope.upPercentBlur = function(){

        var upPercent = angular.element("#upPercent").val();
        if(null == upPercent || upPercent == "" || !/^([0-9]?\.[0-9]+)|0$/.test(upPercent)){

            $scope.addUpPercentIsDisabled = true;
            angular.element("#upPercent").addClass("has-error");
            angular.element("#upPercent").removeClass("has-success");

        }

    }

    var idSave = "";

    $scope.selectMouseDown = function($event){

        var id = angular.element($event.target).attr("id");
        var size = angular.element($event.target).attr("size");
        if(id !== undefined){

            idSave = id;

        }
        angular.element($event.target).attr("size","7");

        angular.element("input:not(#"+ id +")").removeClass("has-success");
        angular.element("select:not(#"+ id +")").removeClass("has-success");

        var selectValue = angular.element("#" + id).val();
        var promptId = id + "Prompt";

        if(id == undefined || size == 7){

            len = 1;

        }else{

            len = 0

        }

        if(len == 0){

            var addHtml = '<div id="selectInputDiv_' + idSave + '" class="align-middle" ><img src="img/arrow/arrow.png" class="select-arrow" /><input type="text" id="selectInput" name="selectInput" class="form-control limit-height" /></div>';
            angular.element($event.target).before(addHtml);

        }


        if(promptId == "typePrompt"){

            angular.element("#" + id + "Prompt").removeClass("select-prompt");
            angular.element("#" + id + "Prompt").addClass("no-select-prompt");

        }else if(promptId == "elementValuePrompt"){

            angular.element("#" + id + "Prompt").removeClass("select-prompt-md");
            angular.element("#" + id + "Prompt").addClass("no-select-prompt");

        }else if(promptId == "generalTypeValuePrompt" || promptId == "currencyTypeValuePrompt"){

            angular.element("#typeValuePrompt").removeClass("select-prompt-ms");
            angular.element("#typeValuePrompt").addClass("no-select-prompt");

        }


    }

    $scope.selectSiteMouseDown = function($event){

        var elementValue = angular.element("#elementValue").val();
        var id = angular.element($event.target).attr("id");

        if(id !== undefined){

            idSave = id;

        }

        angular.element("#typeValuePrompt").removeClass("select-prompt-ms");
        angular.element("#typeValuePrompt").addClass("no-select-prompt");

        if(id == undefined ){

            len = 1;

        }else{

            len = 0

        }

        if(len == 0){

            var addHtml = '<div id="selectInputDiv_' + idSave + '" class="align-middle" ><img src="img/arrow/arrow.png" class="select-arrow" /><input type="text" id="selectInput" name="selectInput" class="form-control limit-height" /></div>';
            angular.element($event.target).before(addHtml);

        }


        if(elementValue == "" || elementValue == undefined || elementValue == null){


        }else{

            angular.element($event.target).attr("size","7");

        }

        angular.element("input:not(#"+ id +")").removeClass("has-success");
        angular.element("select:not(#"+ id +")").removeClass("has-success");

    }

    $scope.selectBlur = function($event){

        var id = angular.element($event.target).attr("id");
        angular.element($event.target).attr("size","0");
        var selectValue = angular.element("#" + id ).val();
        var promptId = id + "Prompt";
        var type = angular.element("#type").val();

        var len = angular.element("#selectInputDiv_" + id).length;

        if(len > 0){

            angular.element("#selectInputDiv_" + id).remove();

        }

        if(null == selectValue || selectValue == ""){

            if(type == 2){

                angular.element("#" + id ).addClass("has-error");
                angular.element("#" + id ).removeClass("has-success");

            }

            if(promptId == "typePrompt"){

                angular.element("#" + id + "Prompt").addClass("select-prompt");
                angular.element("#" + id + "Prompt").removeClass("no-select-prompt");
                angular.element("#" + id ).addClass("has-error");
                angular.element("#" + id ).removeClass("has-success");

            }else if(promptId == "elementValuePrompt"){

                angular.element("#" + id + "Prompt").addClass("select-prompt-md");
                angular.element("#" + id + "Prompt").removeClass("no-select-prompt");

            }else if(promptId == "generalTypeValuePrompt" || promptId == "currencyTypeValuePrompt" || promptId == "siteTypeValuePrompt"){

                angular.element("#typeValuePrompt").addClass("select-prompt-ms");
                angular.element("#typeValuePrompt").removeClass("no-select-prompt");
                angular.element("#" + id ).addClass("has-error");
                angular.element("#" + id ).removeClass("has-success");

            }


        }else{

            angular.element("#" + id ).removeClass("has-error");
            angular.element("#" + id ).addClass("has-success");
            if(promptId == "typePrompt"){

                angular.element("#" + id + "Prompt").removeClass("select-prompt");
                angular.element("#" + id + "Prompt").addClass("no-select-prompt");

            }else if(promptId == "elementValuePrompt"){

                angular.element("#" + id + "Prompt").removeClass("select-prompt-md");
                angular.element("#" + id + "Prompt").addClass("no-select-prompt");

            }else if(promptId == "generalTypeValuePrompt" || promptId == "currencyTypeValuePrompt" || promptId == "siteTypeValuePrompt"){

                angular.element("#typeValuePrompt").removeClass("select-prompt-ms");
                angular.element("#typeValuePrompt").addClass("no-select-prompt");

            }

        }

    }

    $scope.generalFocus = function($event){

        $scope.addIsDisabled = false;
        var id = angular.element($event.target).attr("id");
        angular.element("input:not(#"+ id +")").removeClass("has-success");
        angular.element("select:not(#"+ id +")").removeClass("has-success");

    }

    $scope.addChannelRate = function(){

        var obj = angular.element("#channelRateObjForm").serializeJson();
        var type = angular.element("#type").val();
        if(type == 0){

            obj.typeValue = angular.element("#generalTypeValue").val();

        }else if(type == 1){

            obj.typeValue = angular.element("#currencyTypeValue").val();

        }else if(type == 2){


            obj.typeValue = angular.element("#siteTypeValue").val();

        }
        httpSvc.getData('post','/channelRate/save',obj).then(function (value) {
            if(value.success == 1){

                toaster.pop({
                    type: 'success',
                    title: '汇率添加',
                    body: '添加成功！'
                });

            }else{

                var msg = "添加失败！";
                if(value.msg != ""){

                    msg = msg + value.msg;

                }

                toaster.pop({
                    type: 'error',
                    title: '汇率添加',
                    body: msg
                });

            }

            $uibModalInstance.dismiss();

        });

        $scope.addIsDisabled = true;

    }


}


// 编辑汇率配置
function channelRateInfoEditModalCtrl($scope, $uibModalInstance, httpSvc, toaster,editObj,selectMerchants) {

    $scope.updateIsDisabled = true;

    var type = editObj.type;

    if(type == 0){

        $scope.isGeneralTypeValueSelect = true;
        $scope.isCurrencyTypeSelect = false;
        $scope.isSiteTypeSelect = false;

    }else if(type == 1){

        $scope.isGeneralTypeValueSelect = false;
        $scope.isCurrencyTypeSelect = true;
        $scope.isSiteTypeSelect = false;
        httpSvc.getData('post', '/channelRate/getChannelRateInit',1).then(function (value) {

            $scope.selectCurrencys = value.selectCurrencys;

        });

    }else if(type == 2){

        $scope.isGeneralTypeValueSelect = false;
        $scope.isCurrencyTypeSelect = false;
        $scope.isSiteTypeSelect = true;
        httpSvc.getData('post', '/channelRate/getSitesByParamInit',{merId:editObj.elementValue}).then(function (value) {

            $scope.websites = value.merWebsites;

        });

    }

    $scope.merchants = selectMerchants;

    $scope.channelRate = editObj;

    $scope.channelRate.type = editObj.type + '';

    $scope.optionMouseOver = function($event){


        angular.element($event.target).parent().val("String");


    }

    $scope.optionMouseClick = function($event){

        angular.element($event.target).parent().attr("size",0);
        var id = angular.element($event.target).parent().attr("id");
        angular.element("#selectInputDiv_" + id ).remove();


    }

    $scope.typeChange = function(){

        var type = angular.element("#type").val();

        // 清空子类型数据
        $scope.channelRate.typeValue = "";

        $scope.channelRate.elementValue = "";

        angular.element("#siteTypeValue").find("option:gt(2)").remove();

        angular.element("#elementValuePrompt").text("");

        $scope.updateIsDisabled = true;

        if(type !== undefined && type != null && type !=""){

            if(type == 0 ){

                $scope.isGeneralTypeValueSelect = true;
                $scope.isCurrencyTypeSelect = false;
                $scope.isSiteTypeSelect = false;
                angular.element("#typeValuePrompt").text("需选择元素类型(必选)");
                angular.element("#elementValueLabelId").html('商户号:');

            }else if(type == 1){

                $scope.isGeneralTypeValueSelect = false;
                $scope.isCurrencyTypeSelect = true;
                $scope.isSiteTypeSelect = false;
                angular.element("#typeValuePrompt").text("需选择币种(必选)");
                angular.element("#elementValueLabelId").html('商户号:');

            }else if(type == 2){

                $scope.isGeneralTypeValueSelect = false;
                $scope.isCurrencyTypeSelect = false;
                $scope.isSiteTypeSelect = true;
                angular.element("#typeValuePrompt").text("请先选择商户号,再选择域名(必选)");
                angular.element("#elementValuePrompt").text("需选择商户号(必选)");
                angular.element("#elementValueLabelId").html('<font color="red">*</font>商户号:');
                $scope.updateElementValueIsDisabled = true;

            }


            if(type == 1){

                httpSvc.getData('post', '/channelRate/getChannelRateInit',type).then(function (value) {

                    $scope.selectCurrencys = value.selectCurrencys;

                });

            }

            $scope.updateTypeValueIsDisabled = true;
            $scope.updateIsDisabled = false;
            angular.element("#typePrompt").removeClass("select-prompt");
            angular.element("#typePrompt").addClass("no-select-prompt");

        }else{

            $scope.isGeneralTypeValueSelect = true;
            $scope.isCurrencyTypeSelect = false;
            $scope.isSiteTypeSelect = false;
            $scope.updateIsDisabled = true;
            angular.element("#typePrompt").addClass("select-prompt");
            angular.element("#typePrompt").removeClass("no-select-prompt");


        }

        angular.element("select:not(#type)").removeClass("has-success");
        angular.element("input").removeClass("has-success");

    }

    $scope.currencyTypeValueChange = function(){

        var selectValue = angular.element("#currencyTypeValue").val();
        angular.element("#currencyTypeValue").attr("size","0");

        if(null == selectValue || selectValue == ""){

            $scope.updateTypeValueIsDisabled = true;
            $scope.updateIsDisabled = true;
            angular.element("#typeValuePrompt").addClass("select-prompt-ms");
            angular.element("#typeValuePrompt").removeClass("no-select-prompt");

        }else{

            $scope.updateTypeValueIsDisabled = false;
            $scope.updateIsDisabled = false;
            angular.element("#typeValuePrompt").removeClass("select-prompt-ms");
            angular.element("#typeValuePrompt").addClass("no-select-prompt");

        }

        angular.element("select:not(#currencyTypeValue)").removeClass("has-success");
        $("#selectInputDiv_currencyTypeValue").remove();

    }

    $scope.generalTypeValueChange = function(){

        var selectValue = angular.element("#generalTypeValue").val();

        if(null == selectValue || selectValue == ""){

            $scope.updateTypeValueIsDisabled = true;
            $scope.updateIsDisabled = true;
            angular.element("#typeValuePrompt").addClass("select-prompt-ms");
            angular.element("#typeValuePrompt").removeClass("no-select-prompt");


        }else{

            $scope.updateTypeValueIsDisabled = false;
            $scope.updateIsDisabled = false;
            angular.element("#typeValuePrompt").removeClass("select-prompt-ms");
            angular.element("#typeValuePrompt").addClass("no-select-prompt");

        }

        angular.element("select:not(#generalTypeValue)").removeClass("has-success");

    }


    $scope.siteTypeValueChange = function(){

        var selectValue = angular.element("#siteTypeValue").val();
        angular.element("#siteTypeValue").attr("size","0");

        if(null == selectValue || selectValue == ""){

            $scope.updateTypeValueIsDisabled = true;
            $scope.updateIsDisabled = true;
            angular.element("#typeValuePrompt").addClass("select-prompt-ms");
            angular.element("#typeValuePrompt").removeClass("no-select-prompt");

        }else{

            $scope.updateTypeValueIsDisabled = false;
            $scope.updateIsDisabled = false;
            angular.element("#typeValuePrompt").removeClass("select-prompt-ms");
            angular.element("#typeValuePrompt").addClass("no-select-prompt");

        }

        angular.element("select:not(#siteTypeValue)").removeClass("has-success");
        angular.element("input").removeClass("has-error");
        $("#selectInputDiv_siteTypeValue").remove();


    }

    $scope.elementValueChange = function(){

        var selectValue = angular.element("#elementValue").val();
        var type = angular.element("#type").val();
        angular.element("#elementValue").attr("size","0");

        if(selectValue == "" || selectValue == undefined || selectValue == null){

            angular.element("#elementValuePrompt").addClass("select-prompt-md");
            angular.element("#elementValuePrompt").removeClass("no-select-prompt");

        }else{

            angular.element("#elementValuePrompt").removeClass("select-prompt-md");
            angular.element("#elementValuePrompt").addClass("no-select-prompt");

        }

        var elementValue = angular.element("#elementValue").val();
        var type = angular.element("#type").val();
        if(selectValue !== "" && selectValue !== undefined && selectValue !== null && type == 2){
            httpSvc.getData('post', '/channelRate/getSitesByParamInit',{merId:elementValue}).then(function (value) {

                if( null !== value.merWebsites && value.merWebsites !== undefined){

                    $scope.websites = value.merWebsites;


                }


            });

            $scope.updateIsDisabled = false;
            $scope.updateElementValueIsDisabled = false;

        }else{

            if(type == 2 && (selectValue == "" || selectValue == undefined || selectValue == null)){

                angular.element("#siteTypeValue").find("option:gt(1)").remove();

            }

            $scope.updateIsDisabled = true;
            $scope.updateElementValueIsDisabled = true;

        }

        if(type != 2){

            $scope.updateIsDisabled = false;
            $scope.updateElementValueIsDisabled = false;

        }

        angular.element("select:not(#elementValue)").removeClass("has-success");
        $("#selectInputDiv_elementValue").remove();

    }

    $scope.back = function () {

        $uibModalInstance.dismiss();

    };

    $scope.upPercentFocus = function(){

        $scope.updateUpPercentIsDisabled = false;
        $scope.updateIsDisabled = false;
        angular.element("#upPercent").removeClass("has-error");
        angular.element("#upPercent").addClass("has-success");
        angular.element("input:not(#upPercent)").removeClass("has-success");
        angular.element("select:not(#upPercent)").removeClass("has-success");


    }

    $scope.upPercentBlur = function(){

        var upPercent = angular.element("#upPercent").val();
        if(null == upPercent || upPercent == "" || !/^([0-9]?\.[0-9]+)|0$/.test(upPercent)){

            $scope.updateUpPercentIsDisabled = true;
            $scope.updateIsDisabled = true;
            angular.element("#upPercent").addClass("has-error");
            angular.element("#upPercent").removeClass("has-success");

        }

    }

    var idSave = "";

    $scope.selectMouseDown = function($event){

        var id = angular.element($event.target).attr("id");
        var size = angular.element($event.target).attr("size");
        if(id !== undefined){

            idSave = id;

        }
        angular.element($event.target).attr("size","7");
        angular.element("input:not(#"+ id +")").removeClass("has-success");
        angular.element("select:not(#"+ id +")").removeClass("has-success");

        if(id == undefined || size == 7){

            len = 1;

        }else{

            len = 0

        }

        if(len == 0){

            var addHtml = '<div id="selectInputDiv_' + idSave + '" class="align-middle" ><img src="img/arrow/arrow.png" class="select-arrow" /><input type="text" id="selectInput" name="selectInput" class="form-control limit-height" /></div>';
            angular.element($event.target).before(addHtml);

        }

        var selectValue = angular.element("#" + id).val();
        var promptId = id + "Prompt";

        if(promptId == "typePrompt"){

            angular.element("#" + id + "Prompt").removeClass("select-prompt");
            angular.element("#" + id + "Prompt").addClass("no-select-prompt");

        }else if(promptId == "elementValuePrompt"){

            angular.element("#" + id + "Prompt").removeClass("select-prompt-md");
            angular.element("#" + id + "Prompt").addClass("no-select-prompt");

        }else if(promptId == "generalTypeValuePrompt" || promptId == "currencyTypeValuePrompt"){

            angular.element("#typeValuePrompt").removeClass("select-prompt-ms");
            angular.element("#typeValuePrompt").addClass("no-select-prompt");

        }


    }

    $scope.selectSiteMouseDown = function($event){

        var elementValue = angular.element("#elementValue").val();
        var id = angular.element($event.target).attr("id");
        if(id !== undefined){

            idSave = id;

        }
        angular.element("#typeValuePrompt").removeClass("select-prompt-ms");
        angular.element("#typeValuePrompt").addClass("no-select-prompt");

        if(elementValue == "" || elementValue == undefined || elementValue == null){


        }else{

            angular.element($event.target).attr("size","7");

        }

        if(id == undefined ){

            len = 1;

        }else{

            len = 0

        }

        if(len == 0){

            var addHtml = '<div id="selectInputDiv_' + idSave + '" class="align-middle" ><img src="img/arrow/arrow.png" class="select-arrow" /><input type="text" id="selectInput" name="selectInput" class="form-control limit-height" /></div>';
            angular.element($event.target).before(addHtml);

        }

        angular.element("input:not(#"+ id +")").removeClass("has-success");
        angular.element("select:not(#"+ id +")").removeClass("has-success");

    }

    var cnt = 1;
    $scope.selectBlur = function($event){

        var id = angular.element($event.target).attr("id");
        angular.element($event.target).attr("size","0");
        var selectValue = angular.element("#" + id ).val();
        var promptId = id + "Prompt";
        var type = angular.element("#type").val();

        var len = angular.element("#selectInputDiv_" + id).length;

        if(len > 0){

            angular.element("#selectInputDiv_" + id).remove();

        }

        if(null == selectValue || selectValue == ""){

            if(type != 2){

                angular.element("#" + id ).addClass("has-error");
                angular.element("#" + id ).removeClass("has-success");

            }

            if(cnt == 1){

                $scope.updateIsDisabled = false;
                cnt ++;

            }

            if(promptId == "typePrompt"){

                angular.element("#" + id + "Prompt").addClass("select-prompt");
                angular.element("#" + id + "Prompt").removeClass("no-select-prompt");
                angular.element("#" + id ).addClass("has-error");
                angular.element("#" + id ).removeClass("has-success");

            }else if(promptId == "elementValuePrompt"){

                angular.element("#" + id + "Prompt").addClass("select-prompt-md");
                angular.element("#" + id + "Prompt").removeClass("no-select-prompt");

            }else if(promptId == "generalTypeValuePrompt" || promptId == "currencyTypeValuePrompt" || promptId == "siteTypeValuePrompt"){

                angular.element("#typeValuePrompt").addClass("select-prompt-ms");
                angular.element("#typeValuePrompt").removeClass("no-select-prompt");
                angular.element("#" + id ).addClass("has-error");
                angular.element("#" + id ).removeClass("has-success");
            }


        }else{

            angular.element("#" + id ).removeClass("has-error");
            angular.element("#" + id ).addClass("has-success");
            if(promptId == "typePrompt"){

                angular.element("#" + id + "Prompt").removeClass("select-prompt");
                angular.element("#" + id + "Prompt").addClass("no-select-prompt");

            }else if(promptId == "elementValuePrompt"){

                angular.element("#" + id + "Prompt").removeClass("select-prompt-md");
                angular.element("#" + id + "Prompt").addClass("no-select-prompt");

            }else if(promptId == "generalTypeValuePrompt" || promptId == "currencyTypeValuePrompt" || promptId == "siteTypeValuePrompt"){

                angular.element("#typeValuePrompt").removeClass("select-prompt-ms");
                angular.element("#typeValuePrompt").addClass("no-select-prompt");

            }

        }

    }

    $scope.generalFocus = function($event){

        $scope.updateIsDisabled = false;
        var id = angular.element($event.target).attr("id");
        angular.element("input:not(#"+ id +")").removeClass("has-success");
        angular.element("select:not(#"+ id +")").removeClass("has-success");

    }

    $scope.updateChannelRate = function(){

        var obj = angular.element("#channelRateObjForm").serializeJson();
        var type = angular.element("#type").val();
        if(type == 0){

            obj.typeValue = angular.element("#generalTypeValue").val();

        }else if(type == 1){

            obj.typeValue = angular.element("#currencyTypeValue").val();

        }else if(type == 2){


            obj.typeValue = angular.element("#siteTypeValue").val();

        }
        httpSvc.getData('post','/channelRate/update',obj).then(function (value) {

            if(value.success == 1){

                toaster.pop({
                    type: 'success',
                    title: '汇率编辑',
                    body: '更新成功！'
                });

            }else{

                var msg = "更新失败！";
                if(value.msg != ""){

                    msg = msg + value.msg;

                }

                toaster.pop({
                    type: 'error',
                    title: '汇率编辑',
                    body: msg
                });


            }

            $uibModalInstance.dismiss();

        });

        $scope.updateIsDisabled = true;

    }


}

// 商户订单追踪
function orderTrackInfoCtrl($scope, $uibModal, $document, $filter, toaster, NgTableParams, httpSvc, csvExp) {

    var searchInfo = null;
    $scope.searchOrderTrack = function (data) {

        searchInfo = data;
        $scope.orderTrackTable.page(1);
        $scope.orderTrackTable.reload();

    };

    httpSvc.getData('post', '/trans/getOrderTrackInit').then(function (value) {

        $scope.merchants = value.merchants;
        $scope.payStatusList = value.payStatusList;

    });

    $scope.orderTrackTable = new NgTableParams({}, {
        getData: function (params) {
            angular.element('.ibox-content').addClass('sk-loading');
            return httpSvc.getData('post', '/trans/getOrderTrackInfo', {
                pageFirst: params.page()-1,
                pageSize: params.count(),
                sortFieldName:"trade_time",
                sortType:"desc",
                searchInfo:searchInfo
            }).then(function (value) {

                params.total(value.resultTotal);
                $scope.totalItems = value.resultTotal;
                angular.element('.ibox-content').removeClass('sk-loading');

                return value.orderTrackList;

            });
        }
    });

    $scope.$watch('minTradeTime', function (newVal) {
        if (newVal !== '' && newVal !== undefined && newVal != null) {
            $scope.dateOptions2.minDate = $scope.minTradeTime;
            $scope.maxTradeTimeDisable = false;
            if (oldCreateTime !== '') {
                $scope.maxTradeTime = oldTradeTime;
            }
        } else {
            $scope.maxTradeTimeDisable = true;
            oldTradeTime = $scope.maxTradeTime;
            $scope.maxTradeTime = '';
        }
    });


    var oldTradeTime= '';
    $scope.maxCreateTimeDisable = true;

    $scope.format = 'yyyy/MM/dd';

    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1
    };


    $scope.altInputFormats = ['yyyy/MM/dd'];

    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };


    $scope.resetForm = function () {

        angular.element('#merId').val('');
        angular.element('#merOrderId').val('');
        angular.element('#status').val('');
        angular.element('#refer').val('');
        angular.element('#minTradeTime').val('');
        angular.element('#maxTradeTime').val('');

        $scope.dateOptions1 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.dateOptions2 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.dateOptions3 = {
            formatYear: 'yyyy',
            startingDay: 1
        };
        $scope.dateOptions4 = {
            formatYear: 'yyyy',
            startingDay: 1
        };

        searchInfo = null;

        $scope.maxTradeTimeDisable = true;
        $scope.$broadcast('angucomplete-alt:clearInput');
        $scope.orderTrackTable.page(1);
        $scope.orderTrackTable.reload();

    };

}

// 划款
function transferInfoCtrl($scope, $uibModal, $document, $filter, toaster, NgTableParams, httpSvc,$http, csvExp ) {

    $scope.searchInfo = {};
    $scope.search = function () {

        $scope.transferTable.page(1);
        $scope.transferTable.reload();

    };

    httpSvc.getData('post', '/drawing/getDrawingInit').then(function (value) {

        $scope.merchants = value.merchants;

    });

    $scope.transferTable = new NgTableParams({}, {
        getData: function (params) {
            angular.element('.ibox-content').addClass('sk-loading');
            return httpSvc.getData('post', '/drawing/getDrawingInfo', {
                pageFirst: (params.page()-1)*10,
                pageSize: params.count(),
                sortFieldName:"transfer_time",
                sortType:"desc",
                statusString:"2,3,4,5",
                searchInfo:$scope.searchInfo
            }).then(function (value) {

                $scope.totalItems = value.resultTotal;
                params.total(value.resultTotal);
                angular.element('.ibox-content').removeClass('sk-loading');

                return value.drawingList;

            });
        }
    });

    $scope.$watch('minApplicationTime', function (newVal) {
        if (newVal !== '' && newVal !== undefined && newVal != null) {
            $scope.dateOptions2.minDate = $scope.minApplicationTime;
            $scope.maxApplicationTimeDisable = false;
            if (oldApplicationTime !== '') {
                $scope.maxApplicationTime = oldApplicationTime;
            }
        } else {
            $scope.maxApplicationTimeDisable = true;
            oldApplicationTime = $scope.maxApplicationTime;
            $scope.maxApplicationTime = '';
        }
    });

    $scope.$watch('minTransferTime', function (newVal) {
        if (newVal !== '' && newVal !== undefined && newVal != null) {
            $scope.dateOptions4.minDate = $scope.minTransferTime;
            $scope.maxTransferTimeDisable = false;
            if (oldTransferTimeTime !== '') {
                $scope.maxTransferTime = oldTransferTimeTime;
            }
        } else {
            $scope.maxTransferTimeDisable = true;
            oldTransferTimeTime = $scope.maxTransferTime;
            $scope.maxTransferTime = '';
        }
    });

    var oldApplicationTime= '';
    var oldTransferTimeTime= '';
    $scope.maxApplicationTimeDisable = true;
    $scope.maxTransferTimeDisable = true;

    $scope.format = 'yyyy/MM/dd';

    $scope.dateOptions1 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions2 = {
        formatYear: 'yyyy',
        startingDay: 1
    };

    $scope.dateOptions3 = {
        formatYear: 'yyyy',
        startingDay: 1
    };
    $scope.dateOptions4 = {
        formatYear: 'yyyy',
        startingDay: 1
    };

    $scope.altInputFormats = ['yyyy/MM/dd'];

    $scope.popup1 = {
        opend: false
    };
    $scope.openDatepicker1 = function () {
        $scope.popup1.opend = !$scope.popup1.opend;
    };
    $scope.popup2 = {
        opend: false
    };
    $scope.openDatepicker2 = function () {
        $scope.popup2.opend = !$scope.popup2.opend;
    };


    $scope.popup3 = {

        opend: false
    };

    $scope.openDatepicker3 = function () {
        $scope.popup3.opend = !$scope.popup3.opend;
    };

    $scope.popup4 = {
        opend: false
    };

    $scope.openDatepicker4 = function () {
        $scope.popup4.opend = !$scope.popup4.opend;
    };

    $scope.resetForm = function () {

        $scope.searchInfo = {};
        $scope.transferTable.page(1);
        $scope.transferTable.reload();
    };

    // 划款
    $scope.showCheckModal = function (editObj) {

        var modalInstance = $uibModal.open({
            templateUrl: '/views/financialSection/drawingTransferUpdate',
            controller: 'transferInfoEditModalCtrl',
            resolve: {

                editObj: function () {
                    return editObj;
                }
            }
        });

        modalInstance.result.then(function () {

            $scope.transferTable.page(1);
            $scope.transferTable.reload();


        }, function () {

            $scope.transferTable.page(1);
            $scope.transferTable.reload();

        });
    };

    $scope.$watch('selectedMerchant', function (newVal) {

        if (newVal !== undefined) {

            $scope.searchInfo.refId = newVal.originalObject.id;

        }
    });

    $scope.export = function () {
        var title;
        var content;
        var exportMaxSize = 10000;
        if ($scope.transferTable.total() > exportMaxSize) {
            title = '导出数据';
            content =
                '<div class="text-center">' +
                '<strong>超出系统导出限制数' + exportMaxSize + '条</strong>' +
                '</div>';
            exportModal(title, content).result.then(function () {
            }, function () {
            });
        } else {

            toaster.pop({
                type: 'success',
                title: '导出数据',
                body: '导出中！'
            });
            $http({
                method: 'post',
                url: '/drawing/downloadDrawingInfo',
                data: $scope.searchInfo,
                responseType: 'blob'
            }).then(function (value) {

                var blob = new Blob([value.data], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'});
                var objectUrl = URL.createObjectURL(blob);
                var a = document.createElement("a");
                a.style = "display: none";
                a.href = objectUrl;
                a.download = 'transferlist-' + $filter('date')(Date.now(), 'yyyyMMddHHmmss') + '.xlsx';
                document.body.appendChild(a);
                a.click();
                window.URL.revokeObjectURL(objectUrl);
                a.remove();
                toaster.pop({
                    type: 'success',
                    title: '导出数据',
                    body: '导出数据成功！'
                });
            }, function (reason) {
                toaster.pop({
                    type: 'error',
                    title: '导出数据',
                    body: '导出数据失败！'
                });
                console.log(reason);
            });

        }

        function exportModal(title, content) {
            return $uibModal.open({
                templateUrl: '/views/common/alert_modal',
                controller: 'alertModalCtrl',
                resolve: {
                    title: function () {
                        return title;
                    },
                    content: function () {
                        return content;
                    }
                }
            });
        }
    };

}

//划款打印操作
function transferPrintInfoModalCtrl($scope, $uibModalInstance, httpSvc, toaster,formJsonData) {

    httpSvc.getData('post', '/drawing/getDrawingTransferPrintData',formJsonData).then(function (value) {

        $scope.drawingStatisticsMap = value.drawingStatisticsMap;

        $scope.columns = value.drawingStatisticsMap.transferCurrencyColumns;

        $scope.merchantInfo = value.merchantInfo;
        $scope.merchantSetting = value.merchantSetting;
        $scope.drawing = value.drawing;

        $scope.acquirerNameColumns = value.drawingStatisticsMap.acquirerNameColumns;
        $scope.drawingCurrencyColumns = value.drawingStatisticsMap.drawingCurrencyColumns;
        $scope.drawingAmountColumns = value.drawingStatisticsMap.drawingAmountColumns;
        $scope.transferAmountColumns = value.drawingStatisticsMap.transferAmountColumns;
        $scope.transferRateColumns = value.drawingStatisticsMap.transferRateColumns;

        var drawingCurrencyNumberArray = [];
        var drawingAmountNumberArray = [];
        var transferRateNumberArray = [];
        var transferAmountNumberArray = [];

        for(var i = 1; i < value.drawingStatisticsMap.transferCurrencyColumns ; i++){

            if(i < columns - value.drawingStatisticsMap.drawingCurrencyColumns){

                drawingCurrencyNumberArray.push(i);

            }

            if(i < columns - value.drawingStatisticsMap.drawingAmountColumns){

                drawingAmountNumberArray.push(i);

            }


            if(i < columns - value.drawingStatisticsMap.transferRateColumns){

                transferRateNumberArray.push(i);

            }

            if(i < columns - value.drawingStatisticsMap.transferAmountColumns){

                transferAmountNumberArray.push(i);

            }


        }


    });

    $scope.back = function () {

        $uibModalInstance.dismiss();

    };

    var userAgent = navigator.userAgent; // 取得浏览器的userAgent字符串

    // 判断是否chorme浏览器
    if (userAgent.indexOf("Chrome") > -1){

        $scope.drawingTransferPrint = function (){

            var bdhtml=window.document.body.innerHTML;
            var sprnstr="<!--startprint-->";
            var eprnstr="<!--endprint-->";
            var prnhtml=bdhtml.substr(bdhtml.indexOf(sprnstr)+17);
            var prnhtml=prnhtml.substring(0,prnhtml.indexOf(eprnstr));
            window.document.body.innerHTML=prnhtml;
            window.print();
            window.document.body.innerHTML=bdhtml;
            window.location.href=window.location.href;
            window.location.reload();

        }


    }




}

// 划款操作
function transferInfoEditModalCtrl($scope, $uibModalInstance, httpSvc, toaster,editObj) {

    httpSvc.getData('post', '/drawing/getDrawingTransferUpdateInit',(editObj.refId)).then(function (value) {

        $scope.merchantInfo = value.merchant;
        $scope.merchantSetting = value.merchantSetting;


    });

    $scope.updateIsDisabled = true;

    $scope.drawing = editObj;

    $scope.back = function () {

        $uibModalInstance.dismiss();

    };

    $scope.generalFocus = function($event){

        $scope.updateIsDisabled = false;
        var id = angular.element($event.target).attr("id");
        angular.element("input:not(#"+ id +")").removeClass("has-success");

    }

    $scope.realAmountFocus = function(){

        $scope.updateRealAmountIsDisabled = false;
        angular.element("#realAmount").removeClass("has-error");
        angular.element("#realAmount").addClass("has-success");
        angular.element("input:not(#realAmount)").removeClass("has-success");

    }

    $scope.realAmountBlur = function(){

        var realAmount = angular.element("#realAmount").val();
        if(null == realAmount || realAmount == "" || !(/^\d+(\.\d+)?$/.test(realAmount) || /^\d+(\.\d+)?$/.test(realAmount)) ){

            $scope.updateRealAmountIsDisabled = true;
            angular.element("#realAmount").addClass("has-error");
            angular.element("#realAmount").removeClass("has-success");

        }

    }

    $scope.updateRealAmountRate = function(){

        var obj = angular.element("#drawingTransferObjForm").serializeJson();

        httpSvc.getData('post','/drawing/update',obj).then(function (value) {

            if(value.success == 1){

                toaster.pop({
                    type: 'success',
                    title: '划款',
                    body: '更新成功！'
                });

            }else{

                toaster.pop({
                    type: 'error',
                    title: '划款',
                    body: '更新失败！'
                });


            }

            $uibModalInstance.dismiss();

        });

        $scope.updateIsDisabled = true;

    }

}

/**
 *
 * Pass all functions into module
 */


angular
    .module('inspinia')
    .controller('mainCtrl', mainCtrl)
    .controller('translateCtrl', translateCtrl)
    .controller('homePageCtrl', homePageCtrl)
    .controller('homePagePieCtrl', homePagePieCtrl)
    .controller('homePageDoughnutFCtrl', homePageDoughnutFCtrl)
    .controller('homePageDoughnutRCtrl', homePageDoughnutRCtrl)
    .controller('transInfoCtrl', transInfoCtrl)
    .controller('userMgmtCtrl', userMgmtCtrl)
    .controller('roleMgmtCtrl', roleMgmtCtrl)
    .controller('transModalCtrl', transModalCtrl)
    .controller('transChangeCtrl', transChangeCtrl)
    .controller('transUploadModalCtrl', transUploadModalCtrl)
    .controller('transBondInfoCtrl', transBondInfoCtrl)
    .controller('userRegisterModalCtrl', userRegisterModalCtrl)
    .controller('transChangeModalCtrl', transChangeModalCtrl)
    .controller('userChangeModalCtrl', userChangeModalCtrl)
    .controller('roleModalCtrl', roleModalCtrl)
    .controller('refusedStatisticsCtrl', refusedStatisticsCtrl)
    .controller('acquirerBankCtrl', acquirerBankCtrl)
    .controller('acquirerBankModalCtrl', acquirerBankModalCtrl)
    .controller('acquirerCtrl', acquirerCtrl)
    .controller('acquirerModalCtrl', acquirerModalCtrl)
    .controller('acquirerAccountCtrl',acquirerAccountCtrl)
    .controller('acquirerAccountModalCtrl', acquirerAccountModalCtrl)
    .controller('systemLogCtrl', systemLogCtrl)
    .controller('systemLogModalCtrl', systemLogModalCtrl)
    .controller('merchantMgmtCtrl',merchantMgmtCtrl)
    .controller('merchantInfoCtrl', merchantInfoCtrl)
    .controller('merchantSettingCtrl', merchantSettingCtrl)
    .controller('merchantPayCtrl',merchantPayCtrl)
    .controller('merchantUserMgmtCtrl', merchantUserMgmtCtrl)
    .controller('merchantUserModalCtrl', merchantUserModalCtrl)
    .controller('merchantWebSiteCtrl', merchantWebSiteCtrl)
    .controller('merchantWebSiteModalCtrl', merchantWebSiteModalCtrl)
    .controller('merchantWebSiteRateCtrl', merchantWebSiteRateCtrl)
    .controller('merchantWebsiteProTypeCtrl', merchantWebsiteProTypeCtrl)
    .controller('merchantWebsiteProTypeModalCtrl', merchantWebsiteProTypeModalCtrl)
    .controller('quickTestCtrl', quickTestCtrl)
    .controller('alertModalCtrl', alertModalCtrl)
    .controller('constantInfoCtrl', constantInfoCtrl)
    .controller('businessMoneyInfoCtrl', businessMoneyInfoCtrl)
    .controller('orderChangeInfoCtrl',orderChangeInfoCtrl)
    .controller('constantInfoAddModalCtrl',constantInfoAddModalCtrl)
    .controller('constantInfoEditModalCtrl',constantInfoEditModalCtrl)
    .controller('businessReconMoneyInfoCtrl',businessReconMoneyInfoCtrl)
    .controller('tradeRateInfoCtrl',tradeRateInfoCtrl)
    .controller('tradeRateInfoEditModalCtrl',tradeRateInfoEditModalCtrl)
    .controller('tradeRateInfoAddModalCtrl',tradeRateInfoAddModalCtrl)
    .controller('channelRateInfoCtrl',channelRateInfoCtrl)
    .controller('channelRateInfoEditModalCtrl',channelRateInfoEditModalCtrl)
    .controller('channelRateInfoAddModalCtrl',channelRateInfoAddModalCtrl)
    .controller('riskIndefinitelyCtrl', riskIndefinitelyCtrl)
    .controller('riskIndefinitelyModalCtrl',riskIndefinitelyModalCtrl)
    .controller('riskLimitCtrl',riskLimitCtrl)
    .controller('riskLimitModalCtrl',riskLimitModalCtrl)
    .controller('riskRefusedCtrl',riskRefusedCtrl)
    .controller('riskRefusedModalCtrl',riskRefusedModalCtrl)
    .controller('riskOuterCtrl',riskOuterCtrl)
    .controller('riskOuterModalCtrl',riskOuterModalCtrl)
    .controller('riskBlackcardCtrl',riskBlackcardCtrl)
    .controller('riskBlackcardModalCtrl',riskBlackcardModalCtrl)
    .controller('riskBusinessCtrl',riskBusinessCtrl)
    .controller('riskBusinessModalCtrl',riskBusinessModalCtrl)
    .controller('riskIssuerCtrl',riskIssuerCtrl)
    .controller('riskIssuerModalCtrl',riskIssuerModalCtrl)
    .controller('orderTrackInfoCtrl',orderTrackInfoCtrl)
    .controller('operationAbnormalCtrl',operationAbnormalCtrl)
    .controller('operationAbnormalModalCtrl',operationAbnormalModalCtrl)
    .controller('operationWithdrawalCtrl',operationWithdrawalCtrl)
    .controller('operationWithdrawalModalCtrl',operationWithdrawalModalCtrl)
    .controller('transferInfoCtrl',transferInfoCtrl)
    .controller('transferInfoEditModalCtrl',transferInfoEditModalCtrl)
    .controller('transferPrintInfoModalCtrl',transferPrintInfoModalCtrl);

function getDateStr(AddDayCount) {
    var today = new Date();
    today.setDate(today.getDate() + AddDayCount);// 获取AddDayCount天后的日期
    var y = today.getFullYear();
    var m = today.getMonth() + 1;// 获取当前月份的日期
    var d = today.getDate();
    return y + "-" + m + "-" + d;
}

function verification(value, htmlId) {
    if (value === undefined || value === null || value === '') {
        angular.element(htmlId).parent().removeClass('has-success');
        angular.element(htmlId).parent().addClass('has-error');
        return true;
    } else {
        angular.element(htmlId).parent().removeClass('has-error');
        angular.element(htmlId).parent().addClass('has-success');
        return false;
    }
}

function inputRegex(input, regex, replacement) {
    if (replacement === undefined || replacement === null)
        replacement = '';
    input.value = input.value.replace(regex, replacement);
}

function myRegex($event, regex, flags, replacement) {
    if (replacement === undefined || replacement === null)
        replacement = '';
    var reg = new RegExp(regex, flags);
    $event.target.value = $event.target.value.replace(reg, replacement);
}

//删除数组查找到的数值中第一个的元素
Array.prototype.indexOf = function(val) {
    for (var i = 0; i < this.length; i++) {
        if (this[i] == val) return i;
    }
    return -1;
};

Array.prototype.remove = function(val) {
    var index = this.indexOf(val);
    if (index > -1) {
        this.splice(index, 1);
    }
};